aegis-streaming 0.2.6

Real-time streaming for Aegis database
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
//! Aegis Streaming Subscribers
//!
//! Subscriber management for event subscriptions.
//!
//! @version 0.1.0
//! @author AutomataNexus Development Team

use crate::channel::ChannelId;
use crate::event::EventFilter;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::time::{SystemTime, UNIX_EPOCH};

// =============================================================================
// Subscriber ID
// =============================================================================

/// Unique identifier for a subscriber.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct SubscriberId(pub String);

impl SubscriberId {
    pub fn new(id: impl Into<String>) -> Self {
        Self(id.into())
    }

    pub fn generate() -> Self {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos();
        Self(format!("sub_{:032x}", timestamp))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Display for SubscriberId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<String> for SubscriberId {
    fn from(s: String) -> Self {
        Self(s)
    }
}

impl From<&str> for SubscriberId {
    fn from(s: &str) -> Self {
        Self(s.to_string())
    }
}

// =============================================================================
// Subscription
// =============================================================================

/// A subscription to one or more channels.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Subscription {
    pub id: SubscriberId,
    pub channels: HashSet<ChannelId>,
    pub filter: Option<EventFilter>,
    pub created_at: u64,
    pub active: bool,
    pub metadata: SubscriptionMetadata,
}

impl Subscription {
    /// Create a new subscription.
    pub fn new(id: impl Into<SubscriberId>) -> Self {
        Self {
            id: id.into(),
            channels: HashSet::new(),
            filter: None,
            created_at: current_timestamp(),
            active: true,
            metadata: SubscriptionMetadata::default(),
        }
    }

    /// Add a channel to the subscription.
    pub fn add_channel(&mut self, channel: impl Into<ChannelId>) {
        self.channels.insert(channel.into());
    }

    /// Remove a channel from the subscription.
    pub fn remove_channel(&mut self, channel: &ChannelId) {
        self.channels.remove(channel);
    }

    /// Set the event filter.
    pub fn with_filter(mut self, filter: EventFilter) -> Self {
        self.filter = Some(filter);
        self
    }

    /// Check if subscribed to a channel.
    pub fn is_subscribed_to(&self, channel: &ChannelId) -> bool {
        self.channels.contains(channel)
    }

    /// Deactivate the subscription.
    pub fn deactivate(&mut self) {
        self.active = false;
    }

    /// Reactivate the subscription.
    pub fn activate(&mut self) {
        self.active = true;
    }
}

// =============================================================================
// Subscription Metadata
// =============================================================================

/// Metadata for a subscription.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SubscriptionMetadata {
    pub name: Option<String>,
    pub description: Option<String>,
    pub tags: Vec<String>,
    pub delivery_mode: DeliveryMode,
    pub ack_mode: AckMode,
}

impl SubscriptionMetadata {
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    pub fn with_tag(mut self, tag: impl Into<String>) -> Self {
        self.tags.push(tag.into());
        self
    }

    pub fn with_delivery_mode(mut self, mode: DeliveryMode) -> Self {
        self.delivery_mode = mode;
        self
    }

    pub fn with_ack_mode(mut self, mode: AckMode) -> Self {
        self.ack_mode = mode;
        self
    }
}

// =============================================================================
// Delivery Mode
// =============================================================================

/// Mode for event delivery.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum DeliveryMode {
    /// Events are delivered at most once.
    AtMostOnce,
    /// Events are delivered at least once.
    #[default]
    AtLeastOnce,
    /// Events are delivered exactly once.
    ExactlyOnce,
}

// =============================================================================
// Acknowledgment Mode
// =============================================================================

/// Mode for event acknowledgment.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum AckMode {
    /// Automatic acknowledgment on receive.
    #[default]
    Auto,
    /// Manual acknowledgment required.
    Manual,
    /// No acknowledgment needed.
    None,
}

// =============================================================================
// Subscriber
// =============================================================================

/// A subscriber that receives events.
#[derive(Debug, Clone)]
pub struct Subscriber {
    pub id: SubscriberId,
    pub subscriptions: Vec<Subscription>,
    pub created_at: u64,
    pub last_active: u64,
    pub events_received: u64,
    pub events_acknowledged: u64,
}

impl Subscriber {
    /// Create a new subscriber.
    pub fn new(id: impl Into<SubscriberId>) -> Self {
        let now = current_timestamp();
        Self {
            id: id.into(),
            subscriptions: Vec::new(),
            created_at: now,
            last_active: now,
            events_received: 0,
            events_acknowledged: 0,
        }
    }

    /// Add a subscription.
    pub fn add_subscription(&mut self, subscription: Subscription) {
        self.subscriptions.push(subscription);
    }

    /// Remove a subscription.
    pub fn remove_subscription(&mut self, subscription_id: &SubscriberId) {
        self.subscriptions.retain(|s| &s.id != subscription_id);
    }

    /// Get active subscriptions.
    pub fn active_subscriptions(&self) -> Vec<&Subscription> {
        self.subscriptions.iter().filter(|s| s.active).collect()
    }

    /// Record an event received.
    pub fn record_received(&mut self) {
        self.events_received += 1;
        self.last_active = current_timestamp();
    }

    /// Record an event acknowledged.
    pub fn record_acknowledged(&mut self) {
        self.events_acknowledged += 1;
    }

    /// Check if the subscriber is active.
    pub fn is_active(&self) -> bool {
        !self.subscriptions.is_empty() && self.subscriptions.iter().any(|s| s.active)
    }
}

fn current_timestamp() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0)
}

// =============================================================================
// Consumer Group
// =============================================================================

/// A consumer group that coordinates message consumption across multiple subscribers.
///
/// Each member is assigned a set of channels, and the group tracks committed offsets
/// per channel so that consumers can resume from where they left off.
#[derive(Debug, Clone)]
pub struct ConsumerGroup {
    /// Unique identifier for this consumer group.
    pub group_id: String,
    /// Map of subscriber_id -> set of assigned channel names.
    pub members: HashMap<SubscriberId, HashSet<String>>,
    /// Map of channel_name -> committed offset.
    pub committed_offsets: HashMap<String, u64>,
    /// Timestamp when the group was created.
    pub created_at: u64,
}

impl ConsumerGroup {
    /// Create a new consumer group with the given ID.
    pub fn new(group_id: impl Into<String>) -> Self {
        Self {
            group_id: group_id.into(),
            members: HashMap::new(),
            committed_offsets: HashMap::new(),
            created_at: current_timestamp(),
        }
    }

    /// Add a member to the consumer group with an initial set of assigned channels.
    pub fn add_member(&mut self, subscriber_id: SubscriberId, channels: HashSet<String>) {
        self.members.insert(subscriber_id, channels);
    }

    /// Remove a member from the consumer group. Returns the channels that were assigned
    /// to the removed member, or None if the member was not found.
    pub fn remove_member(&mut self, subscriber_id: &SubscriberId) -> Option<HashSet<String>> {
        self.members.remove(subscriber_id)
    }

    /// Commit an offset for a channel. This records the position up to which
    /// messages have been successfully processed.
    pub fn commit_offset(&mut self, channel_name: impl Into<String>, offset: u64) {
        self.committed_offsets.insert(channel_name.into(), offset);
    }

    /// Get the committed offset for a channel. Returns None if no offset
    /// has been committed for that channel.
    pub fn get_offset(&self, channel_name: &str) -> Option<u64> {
        self.committed_offsets.get(channel_name).copied()
    }

    /// Get the number of members in the group.
    pub fn member_count(&self) -> usize {
        self.members.len()
    }

    /// Check if a subscriber is a member of this group.
    pub fn is_member(&self, subscriber_id: &SubscriberId) -> bool {
        self.members.contains_key(subscriber_id)
    }

    /// Get the channels assigned to a specific member.
    pub fn get_member_channels(&self, subscriber_id: &SubscriberId) -> Option<&HashSet<String>> {
        self.members.get(subscriber_id)
    }
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_subscriber_id() {
        let id1 = SubscriberId::generate();
        let id2 = SubscriberId::generate();
        assert_ne!(id1, id2);
        assert!(id1.as_str().starts_with("sub_"));
    }

    #[test]
    fn test_subscription() {
        let mut subscription = Subscription::new("sub1");
        subscription.add_channel("channel1");
        subscription.add_channel("channel2");

        assert!(subscription.is_subscribed_to(&ChannelId::new("channel1")));
        assert!(!subscription.is_subscribed_to(&ChannelId::new("channel3")));
        assert!(subscription.active);

        subscription.deactivate();
        assert!(!subscription.active);
    }

    #[test]
    fn test_subscriber() {
        let mut subscriber = Subscriber::new("user1");

        let mut sub1 = Subscription::new("sub1");
        sub1.add_channel("events");
        subscriber.add_subscription(sub1);

        assert!(subscriber.is_active());
        assert_eq!(subscriber.active_subscriptions().len(), 1);

        subscriber.record_received();
        assert_eq!(subscriber.events_received, 1);
    }

    #[test]
    fn test_subscription_metadata() {
        let metadata = SubscriptionMetadata::default()
            .with_name("Test Subscription")
            .with_description("A test subscription")
            .with_tag("test")
            .with_delivery_mode(DeliveryMode::ExactlyOnce);

        assert_eq!(metadata.name, Some("Test Subscription".to_string()));
        assert_eq!(metadata.delivery_mode, DeliveryMode::ExactlyOnce);
    }

    #[test]
    fn test_consumer_group_creation() {
        let group = ConsumerGroup::new("group1");
        assert_eq!(group.group_id, "group1");
        assert_eq!(group.member_count(), 0);
        assert!(group.committed_offsets.is_empty());
        assert!(group.created_at > 0);
    }

    #[test]
    fn test_consumer_group_add_remove_members() {
        let mut group = ConsumerGroup::new("group1");

        let sub1 = SubscriberId::new("sub1");
        let sub2 = SubscriberId::new("sub2");

        let mut channels1 = HashSet::new();
        channels1.insert("events".to_string());
        channels1.insert("logs".to_string());

        let mut channels2 = HashSet::new();
        channels2.insert("metrics".to_string());

        group.add_member(sub1.clone(), channels1);
        group.add_member(sub2.clone(), channels2);

        assert_eq!(group.member_count(), 2);
        assert!(group.is_member(&sub1));
        assert!(group.is_member(&sub2));

        let member_channels = group.get_member_channels(&sub1).unwrap();
        assert!(member_channels.contains("events"));
        assert!(member_channels.contains("logs"));

        let removed = group.remove_member(&sub1);
        assert!(removed.is_some());
        assert_eq!(group.member_count(), 1);
        assert!(!group.is_member(&sub1));

        // Removing a non-existent member returns None
        let removed = group.remove_member(&SubscriberId::new("nonexistent"));
        assert!(removed.is_none());
    }

    #[test]
    fn test_consumer_group_offset_tracking() {
        let mut group = ConsumerGroup::new("group1");

        // No offset committed yet
        assert_eq!(group.get_offset("events"), None);

        group.commit_offset("events", 42);
        assert_eq!(group.get_offset("events"), Some(42));

        // Update offset
        group.commit_offset("events", 100);
        assert_eq!(group.get_offset("events"), Some(100));

        // Different channel
        group.commit_offset("logs", 5);
        assert_eq!(group.get_offset("logs"), Some(5));
        assert_eq!(group.get_offset("events"), Some(100));
    }
}