kuberator 0.4.0

A Kubernetes operator framework in Rust
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
//! Kubernetes event emission for operators.
//!
//! This module provides generic event emission functionality for Kubernetes operators.
//! Events are observability-only and never fail reconciliation.
//!
//! Events use the `events.k8s.io/v1` API with built-in deduplication: the first
//! occurrence creates a new Event, and subsequent identical events increment the
//! series count via PATCH instead of creating duplicates.
//!
//! # Example
//! ```rust,ignore
//! use kuberator::events::{EmitEvent, EventRecorder, EventData, Reason};
//! use kuberator::cache::StaticApiProvider;
//! use kuberator::cache::CachingStrategy;
//! use strum::{Display, AsRefStr};
//! use std::sync::Arc;
//!
//! #[derive(Debug, Clone, Copy, Display, AsRefStr)]
//! enum MyEventReason {
//!     ResourceCreated,
//!     ResourceUpdated,
//! }
//! impl Reason for MyEventReason {}
//!
//! // In your operator setup:
//! let event_api_provider = Arc::new(StaticApiProvider::new(
//!     client,
//!     vec!["default"],
//!     CachingStrategy::Adhoc,
//! ));
//!
//! let event_recorder = Arc::new(EventRecorder::new(
//!     event_api_provider,
//!     "my-operator"
//! ));
//!
//! // In your reconciliation:
//! event_recorder.emit(
//!     &resource,
//!     EventData::normal(MyEventReason::ResourceCreated, "Resource was created")
//! ).await;
//! ```

pub mod types;

mod recorder;

pub use recorder::EventRecorder;
pub use types::EventData;
pub use types::EventType;
pub use types::Reason;

use async_trait::async_trait;
use kube::Resource;

use crate::error::Result;
use crate::TryResource;

/// Trait for emitting Kubernetes events
#[async_trait]
pub trait EmitEvent<R>: Send + Sync
where
    R: Reason,
{
    /// Try to emit a Kubernetes event, returning any errors
    ///
    /// Use this when you need explicit error handling. For most cases,
    /// prefer `emit()` which logs errors without failing reconciliation.
    async fn try_emit<K>(&self, object: &K, event: EventData<R>) -> Result<()>
    where
        K: Resource<DynamicType = ()> + TryResource + Clone + Send + Sync;

    /// Emit a Kubernetes event, logging but not propagating errors
    ///
    /// Events are observability only and should not fail reconciliation.
    /// This is the primary API for emitting events in reconciliation loops.
    async fn emit<K>(&self, object: &K, event: EventData<R>)
    where
        K: Resource<DynamicType = ()> + TryResource + Clone + Send + Sync,
    {
        let reason = event.reason.to_owned();
        if let Err(e) = self.try_emit(object, event).await {
            tracing::warn!(
                error = %e,
                reason = %reason,
                "Failed to emit event"
            );
        }
    }
}

#[cfg(test)]
pub mod tests {
    use super::*;
    use crate::error::Error;
    use crate::events::types::EventType;
    use k8s_openapi::api::core::v1::ConfigMap;
    use k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta;
    use std::sync::Arc;
    use std::sync::Mutex;
    use strum::AsRefStr;
    use strum::Display;

    // Test event reason enum
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Display, AsRefStr)]
    pub enum TestEventReason {
        ResourceCreated,
        ResourceUpdated,
        ResourceDeleted,
        ReconciliationFailed,
    }

    impl Reason for TestEventReason {}

    /// A recorded event with deduplication tracking
    #[derive(Debug, Clone)]
    pub struct RecordedEvent<R: Reason> {
        pub resource_name: String,
        pub reason: R,
        pub message: String,
        pub count: i32,
    }

    /// Mock event recorder for testing with deduplication behavior
    #[derive(Clone)]
    pub struct MockEventRecorder<R: Reason> {
        events: Arc<Mutex<Vec<RecordedEvent<R>>>>,
    }

    impl<R: Reason> Default for MockEventRecorder<R> {
        fn default() -> Self {
            Self::new()
        }
    }

    impl<R: Reason> MockEventRecorder<R> {
        pub fn new() -> Self {
            Self {
                events: Arc::new(Mutex::new(Vec::new())),
            }
        }

        /// Returns deduplicated events with counts
        pub fn events(&self) -> Vec<RecordedEvent<R>> {
            self.events.lock().unwrap().clone()
        }

        /// Returns the number of unique events
        pub fn event_count(&self) -> usize {
            self.events.lock().unwrap().len()
        }

        pub fn clear(&self) {
            self.events.lock().unwrap().clear();
        }
    }

    #[async_trait]
    impl<R: Reason> EmitEvent<R> for MockEventRecorder<R> {
        async fn try_emit<K>(&self, object: &K, event: EventData<R>) -> Result<()>
        where
            K: Resource<DynamicType = ()> + TryResource + Clone + Send + Sync,
        {
            let name = object.try_name()?.to_owned();
            let reason_str = event.reason.as_ref().to_owned();

            let mut events = self.events.lock().unwrap();

            // Dedup: find existing event with same resource_name + reason
            if let Some(existing) = events
                .iter_mut()
                .find(|e| e.resource_name == name && e.reason.as_ref() == reason_str)
            {
                existing.count += 1;
                existing.message = event.message;
                return Ok(());
            }

            events.push(RecordedEvent {
                resource_name: name,
                reason: event.reason,
                message: event.message,
                count: 1,
            });

            Ok(())
        }
    }

    /// Mock that can be configured to fail on demand for testing error handling
    struct FailingMockEventRecorder<R: Reason> {
        should_fail: bool,
        events: Arc<Mutex<Vec<RecordedEvent<R>>>>,
    }

    impl<R: Reason> FailingMockEventRecorder<R> {
        fn new_succeeding() -> Self {
            Self {
                should_fail: false,
                events: Arc::new(Mutex::new(Vec::new())),
            }
        }

        fn new_failing() -> Self {
            Self {
                should_fail: true,
                events: Arc::new(Mutex::new(Vec::new())),
            }
        }

        fn events(&self) -> Vec<RecordedEvent<R>> {
            self.events.lock().unwrap().clone()
        }
    }

    #[async_trait]
    impl<R: Reason> EmitEvent<R> for FailingMockEventRecorder<R> {
        async fn try_emit<K>(&self, object: &K, event: EventData<R>) -> Result<()>
        where
            K: Resource<DynamicType = ()> + TryResource + Clone + Send + Sync,
        {
            if self.should_fail {
                return Err(Error::EmitEventFailed("Simulated failure".to_string()));
            }

            let name = object.try_name()?.to_owned();
            let reason_str = event.reason.as_ref().to_owned();

            let mut events = self.events.lock().unwrap();

            if let Some(existing) = events
                .iter_mut()
                .find(|e| e.resource_name == name && e.reason.as_ref() == reason_str)
            {
                existing.count += 1;
                existing.message = event.message;
                return Ok(());
            }

            events.push(RecordedEvent {
                resource_name: name,
                reason: event.reason,
                message: event.message,
                count: 1,
            });

            Ok(())
        }
    }

    fn create_test_resource() -> ConfigMap {
        ConfigMap {
            metadata: ObjectMeta {
                name: Some("test-resource".to_string()),
                namespace: Some("default".to_string()),
                ..Default::default()
            },
            ..Default::default()
        }
    }

    #[tokio::test]
    async fn test_mock_event_recorder() {
        // Given: A mock event recorder and a resource
        let recorder = MockEventRecorder::<TestEventReason>::new();
        let resource = create_test_resource();

        // When: Emitting a single event
        recorder
            .try_emit(
                &resource,
                EventData::normal(TestEventReason::ResourceCreated, "Resource was created"),
            )
            .await
            .unwrap();

        // Then: One event is recorded with correct fields
        let events = recorder.events();
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].resource_name, "test-resource");
        assert_eq!(events[0].reason, TestEventReason::ResourceCreated);
        assert_eq!(events[0].message, "Resource was created");
        assert_eq!(events[0].count, 1);
    }

    #[test]
    fn test_normal_event_creation() {
        // Given: A reason and message
        let reason = TestEventReason::ResourceCreated;
        let message = "Resource has been created successfully";

        // When: Creating a normal event
        let event = EventData::normal(reason, message);

        // Then: The event has correct type, reason, and message
        assert_eq!(event.type_, EventType::Normal);
        assert_eq!(event.reason, TestEventReason::ResourceCreated);
        assert_eq!(event.message, "Resource has been created successfully");
        assert_eq!(event.action, None);
    }

    #[test]
    fn test_warning_event_creation() {
        // Given: A reason and message
        let reason = TestEventReason::ReconciliationFailed;
        let message = "Failed to reconcile resource configuration";

        // When: Creating a warning event
        let event = EventData::warning(reason, message);

        // Then: The event has Warning type
        assert_eq!(event.type_, EventType::Warning);
        assert_eq!(event.reason, TestEventReason::ReconciliationFailed);
        assert_eq!(event.message, "Failed to reconcile resource configuration");
        assert_eq!(event.action, None);
    }

    #[test]
    fn test_event_with_action() {
        // Given: A normal event
        let event = EventData::normal(TestEventReason::ResourceCreated, "Resource created");

        // When: Adding an action
        let event = event.with_action("CreateResource");

        // Then: The event has the action set
        assert_eq!(event.action, Some("CreateResource".to_string()));
    }

    #[test]
    fn test_event_message_accepts_string() {
        // Given: A String instead of &str
        let message = String::from("Dynamic message");

        // When: Creating an event with String
        let event = EventData::normal(TestEventReason::ResourceCreated, message);

        // Then: The message is correctly stored
        assert_eq!(event.message, "Dynamic message");
    }

    #[tokio::test]
    async fn test_try_emit_success_returns_ok() {
        // Given: A successful event recorder and a resource
        let recorder = FailingMockEventRecorder::new_succeeding();
        let resource = create_test_resource();

        // When: Calling try_emit with a normal event
        let result = recorder
            .try_emit(
                &resource,
                EventData::normal(TestEventReason::ResourceCreated, "Test message"),
            )
            .await;

        // Then: The result is Ok and the event was recorded
        assert!(result.is_ok());
        let events = recorder.events();
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].resource_name, "test-resource");
        assert_eq!(events[0].message, "Test message");
    }

    #[tokio::test]
    async fn test_try_emit_failure_returns_error() {
        // Given: A failing event recorder and a resource
        let recorder = FailingMockEventRecorder::new_failing();
        let resource = create_test_resource();

        // When: Calling try_emit
        let result = recorder
            .try_emit(
                &resource,
                EventData::normal(TestEventReason::ResourceCreated, "Test message"),
            )
            .await;

        // Then: The result is an error
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Simulated failure"));
    }

    #[tokio::test]
    async fn test_emit_success_completes_without_error() {
        // Given: A successful event recorder and a resource
        let recorder = FailingMockEventRecorder::new_succeeding();
        let resource = create_test_resource();

        // When: Calling emit (silent-fail version)
        recorder
            .emit(
                &resource,
                EventData::normal(TestEventReason::ResourceCreated, "Test message"),
            )
            .await;

        // Then: The event was recorded (no panic, no error propagation)
        let events = recorder.events();
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].resource_name, "test-resource");
    }

    #[tokio::test]
    async fn test_emit_failure_swallows_error_and_continues() {
        // Given: A failing event recorder and a resource
        let recorder = FailingMockEventRecorder::new_failing();
        let resource = create_test_resource();

        // When: Calling emit (should not panic or propagate error)
        recorder
            .emit(
                &resource,
                EventData::normal(TestEventReason::ResourceCreated, "Test message"),
            )
            .await;

        // Then: No panic occurred and no events were recorded (failure was swallowed)
        let events = recorder.events();
        assert_eq!(events.len(), 0);
    }

    #[tokio::test]
    async fn test_emit_calls_try_emit_internally() {
        // Given: A successful event recorder
        let recorder = FailingMockEventRecorder::new_succeeding();
        let resource = create_test_resource();

        // When: Calling emit
        recorder
            .emit(
                &resource,
                EventData::normal(TestEventReason::ResourceUpdated, "Update message"),
            )
            .await;

        // Then: try_emit was called (evidenced by recorded event)
        let events = recorder.events();
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].reason, TestEventReason::ResourceUpdated);
        assert_eq!(events[0].message, "Update message");
    }

    #[tokio::test]
    async fn test_multiple_different_events_are_recorded() {
        // Given: A recorder and a resource
        let recorder = MockEventRecorder::<TestEventReason>::new();
        let resource = create_test_resource();

        // When: Emitting multiple events with different reasons
        recorder
            .emit(
                &resource,
                EventData::normal(TestEventReason::ResourceCreated, "Created"),
            )
            .await;

        recorder
            .emit(
                &resource,
                EventData::normal(TestEventReason::ResourceUpdated, "Updated"),
            )
            .await;

        recorder
            .emit(
                &resource,
                EventData::normal(TestEventReason::ResourceDeleted, "Deleted"),
            )
            .await;

        // Then: All events are recorded separately (different reasons = no dedup)
        let events = recorder.events();
        assert_eq!(events.len(), 3);
        assert_eq!(events[0].reason, TestEventReason::ResourceCreated);
        assert_eq!(events[1].reason, TestEventReason::ResourceUpdated);
        assert_eq!(events[2].reason, TestEventReason::ResourceDeleted);
    }

    #[tokio::test]
    async fn test_clear_removes_all_events() {
        // Given: A recorder with some events
        let recorder = MockEventRecorder::<TestEventReason>::new();
        let resource = create_test_resource();

        recorder
            .emit(
                &resource,
                EventData::normal(TestEventReason::ResourceCreated, "Created"),
            )
            .await;

        assert_eq!(recorder.events().len(), 1);

        // When: Clearing the events
        recorder.clear();

        // Then: All events are removed
        assert_eq!(recorder.events().len(), 0);
    }

    #[tokio::test]
    async fn test_duplicate_events_are_deduplicated() {
        // Given: A recorder and a resource
        let recorder = MockEventRecorder::<TestEventReason>::new();
        let resource = create_test_resource();

        // When: Emitting the same event (same resource + reason) twice
        recorder
            .emit(
                &resource,
                EventData::normal(TestEventReason::ResourceCreated, "First message"),
            )
            .await;

        recorder
            .emit(
                &resource,
                EventData::normal(TestEventReason::ResourceCreated, "Second message"),
            )
            .await;

        // Then: Only one event exists with count=2 and the latest message
        let events = recorder.events();
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].reason, TestEventReason::ResourceCreated);
        assert_eq!(events[0].message, "Second message");
        assert_eq!(events[0].count, 2);
    }

    #[tokio::test]
    async fn test_different_reasons_not_deduplicated() {
        // Given: A recorder and a resource
        let recorder = MockEventRecorder::<TestEventReason>::new();
        let resource = create_test_resource();

        // When: Emitting events with different reasons for the same resource
        recorder
            .emit(
                &resource,
                EventData::normal(TestEventReason::ResourceCreated, "Created"),
            )
            .await;

        recorder
            .emit(
                &resource,
                EventData::warning(TestEventReason::ReconciliationFailed, "Failed"),
            )
            .await;

        // Then: Both events are recorded separately
        let events = recorder.events();
        assert_eq!(events.len(), 2);
        assert_eq!(events[0].count, 1);
        assert_eq!(events[1].count, 1);
    }

    #[tokio::test]
    async fn test_different_resources_not_deduplicated() {
        // Given: A recorder and two different resources
        let recorder = MockEventRecorder::<TestEventReason>::new();
        let resource1 = ConfigMap {
            metadata: ObjectMeta {
                name: Some("resource-1".to_string()),
                namespace: Some("default".to_string()),
                ..Default::default()
            },
            ..Default::default()
        };
        let resource2 = ConfigMap {
            metadata: ObjectMeta {
                name: Some("resource-2".to_string()),
                namespace: Some("default".to_string()),
                ..Default::default()
            },
            ..Default::default()
        };

        // When: Emitting the same reason for different resources
        recorder
            .emit(
                &resource1,
                EventData::normal(TestEventReason::ResourceCreated, "Created 1"),
            )
            .await;

        recorder
            .emit(
                &resource2,
                EventData::normal(TestEventReason::ResourceCreated, "Created 2"),
            )
            .await;

        // Then: Both events are recorded separately
        let events = recorder.events();
        assert_eq!(events.len(), 2);
        assert_eq!(events[0].resource_name, "resource-1");
        assert_eq!(events[1].resource_name, "resource-2");
    }

    #[tokio::test]
    async fn test_event_count_returns_unique_count() {
        // Given: A recorder with some events
        let recorder = MockEventRecorder::<TestEventReason>::new();
        let resource = create_test_resource();

        // When: Emitting 3 events (2 duplicates + 1 different)
        recorder
            .emit(&resource, EventData::normal(TestEventReason::ResourceCreated, "First"))
            .await;
        recorder
            .emit(&resource, EventData::normal(TestEventReason::ResourceCreated, "Second"))
            .await;
        recorder
            .emit(
                &resource,
                EventData::normal(TestEventReason::ResourceUpdated, "Updated"),
            )
            .await;

        // Then: event_count returns 2 unique events
        assert_eq!(recorder.event_count(), 2);
    }
}