rusmes-jmap 0.1.2

JMAP server for RusMES โ€” RFC 8620/8621 HTTP/JSON mail API with Email, Mailbox, Thread, Blob, EventSource push, and VacationResponse support
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
//! EventSource (Server-Sent Events) endpoint for JMAP
//!
//! Implements RFC 8620 Section 7.3:
//! - `GET /eventsource` โ€” Server-Sent Events push channel for state-change notifications
//! - State change notifications
//! - Push subscription management
//!
//! ## Mount Point
//!
//! This route is mounted by [`crate::api::JmapServer::routes_with_auth_and_state`]
//! behind the [`crate::auth::require_auth`] middleware. The handler requires a
//! valid authenticated session before establishing the SSE stream.
//!
//! Per-account event filtering (ensuring that one user cannot receive another
//! user's state-change pushes) is a follow-up concern and is not yet implemented
//! here.

use axum::{
    extract::{Query, State},
    response::sse::{Event, KeepAlive, Sse},
    routing::get,
    Router,
};
use futures::stream::Stream;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::convert::Infallible;
use std::sync::{Arc, RwLock};
use std::time::Duration;
use tokio::sync::broadcast;

/// EventSource state manager
#[derive(Clone)]
pub struct EventSourceManager {
    /// Broadcast channel for state changes
    tx: broadcast::Sender<StateChange>,
    /// Current state per data type
    states: Arc<RwLock<HashMap<String, String>>>,
}

/// State change event
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StateChange {
    /// Data types that changed
    pub changed: HashMap<String, String>,
}

/// EventSource push filter hint (not the full RFC 8620 ยง5.1 PushSubscription resource).
///
/// This lightweight struct records the URL + type filter for a single SSE stream
/// connection.  The full RFC 8620 `PushSubscription` resource lives in
/// `crate::types::PushSubscription`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EventSourcePushHint {
    /// Push subscription URL
    pub url: String,
    /// Types to monitor
    #[serde(skip_serializing_if = "Option::is_none")]
    pub types: Option<Vec<String>>,
}

/// EventSource query parameters
#[derive(Debug, Deserialize)]
pub struct EventSourceQuery {
    /// Data types to monitor (comma-separated)
    #[serde(default)]
    pub types: Option<String>,
    /// Close after this many seconds
    #[serde(default)]
    pub closeafter: Option<u64>,
    /// Ping interval in seconds
    #[serde(default)]
    pub ping: Option<u64>,
}

impl EventSourceManager {
    /// Create new EventSource manager
    pub fn new() -> Self {
        let (tx, _rx) = broadcast::channel(100);
        Self {
            tx,
            states: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// Notify state change
    pub fn notify_change(&self, data_type: String, new_state: String) {
        // Update stored state
        if let Ok(mut states) = self.states.write() {
            states.insert(data_type.clone(), new_state.clone());
        }

        // Broadcast change
        let mut changed = HashMap::new();
        changed.insert(data_type, new_state);

        let state_change = StateChange { changed };

        // Ignore send errors (no active listeners)
        let _ = self.tx.send(state_change);
    }

    /// Get current state for a data type
    pub fn get_state(&self, data_type: &str) -> Option<String> {
        self.states
            .read()
            .ok()
            .and_then(|states| states.get(data_type).cloned())
    }

    /// Subscribe to state changes
    fn subscribe(&self) -> broadcast::Receiver<StateChange> {
        self.tx.subscribe()
    }
}

impl Default for EventSourceManager {
    fn default() -> Self {
        Self::new()
    }
}

/// Create EventSource router.
///
/// Mounts:
/// - `GET /eventsource` โ€” Server-Sent Events push channel (RFC 8620 ยง7.3)
pub fn eventsource_routes() -> Router<EventSourceManager> {
    Router::new().route("/eventsource", get(eventsource_handler))
}

/// EventSource SSE handler
async fn eventsource_handler(
    Query(params): Query<EventSourceQuery>,
    State(manager): State<EventSourceManager>,
) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
    // Parse types filter
    let types_filter: Option<Vec<String>> = params
        .types
        .map(|t| t.split(',').map(|s| s.trim().to_string()).collect());

    // Subscribe to state changes
    let mut rx = manager.subscribe();

    // Determine close timeout
    let close_after = params.closeafter.map(Duration::from_secs);

    // Determine ping interval
    let ping_interval = params
        .ping
        .map(Duration::from_secs)
        .unwrap_or(Duration::from_secs(30));

    // Create event stream
    let stream = async_stream::stream! {
        let start_time = tokio::time::Instant::now();

        loop {
            // Check if we should close
            if let Some(timeout) = close_after {
                if start_time.elapsed() >= timeout {
                    break;
                }
            }

            // Wait for next event or ping timeout
            tokio::select! {
                result = rx.recv() => {
                    match result {
                        Ok(state_change) => {
                            // Filter by types if specified
                            let filtered_changes: HashMap<String, String> = if let Some(ref filter) = types_filter {
                                state_change.changed.into_iter()
                                    .filter(|(k, _)| filter.contains(k))
                                    .collect()
                            } else {
                                state_change.changed
                            };

                            // Only send if there are changes after filtering
                            if !filtered_changes.is_empty() {
                                let event_data = StateChange { changed: filtered_changes };
                                if let Ok(json) = serde_json::to_string(&event_data) {
                                    yield Ok(Event::default()
                                        .event("state")
                                        .data(json));
                                }
                            }
                        }
                        Err(broadcast::error::RecvError::Lagged(_)) => {
                            // Client fell behind, send error event
                            yield Ok(Event::default()
                                .event("error")
                                .data("Client lagged behind"));
                        }
                        Err(broadcast::error::RecvError::Closed) => {
                            // Channel closed, end stream
                            break;
                        }
                    }
                }
                _ = tokio::time::sleep(ping_interval) => {
                    // Send ping to keep connection alive
                    yield Ok(Event::default().comment("ping"));
                }
            }
        }
    };

    Sse::new(stream).keep_alive(KeepAlive::default())
}

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

    #[test]
    fn test_event_source_manager_new() {
        let manager = EventSourceManager::new();
        assert!(manager.get_state("Email").is_none());
    }

    #[test]
    fn test_notify_change() {
        let manager = EventSourceManager::new();

        manager.notify_change("Email".to_string(), "state1".to_string());

        assert_eq!(manager.get_state("Email"), Some("state1".to_string()));
    }

    #[test]
    fn test_notify_multiple_changes() {
        let manager = EventSourceManager::new();

        manager.notify_change("Email".to_string(), "state1".to_string());
        manager.notify_change("Mailbox".to_string(), "state2".to_string());
        manager.notify_change("Thread".to_string(), "state3".to_string());

        assert_eq!(manager.get_state("Email"), Some("state1".to_string()));
        assert_eq!(manager.get_state("Mailbox"), Some("state2".to_string()));
        assert_eq!(manager.get_state("Thread"), Some("state3".to_string()));
    }

    #[test]
    fn test_state_update() {
        let manager = EventSourceManager::new();

        manager.notify_change("Email".to_string(), "state1".to_string());
        assert_eq!(manager.get_state("Email"), Some("state1".to_string()));

        manager.notify_change("Email".to_string(), "state2".to_string());
        assert_eq!(manager.get_state("Email"), Some("state2".to_string()));
    }

    #[test]
    fn test_subscribe() {
        let manager = EventSourceManager::new();
        let mut rx = manager.subscribe();

        manager.notify_change("Email".to_string(), "state1".to_string());

        let change = rx.try_recv().unwrap();
        assert_eq!(change.changed.get("Email"), Some(&"state1".to_string()));
    }

    #[test]
    fn test_multiple_subscribers() {
        let manager = EventSourceManager::new();
        let mut rx1 = manager.subscribe();
        let mut rx2 = manager.subscribe();

        manager.notify_change("Email".to_string(), "state1".to_string());

        // Both should receive the change
        let change1 = rx1.try_recv().unwrap();
        let change2 = rx2.try_recv().unwrap();

        assert_eq!(change1.changed.get("Email"), Some(&"state1".to_string()));
        assert_eq!(change2.changed.get("Email"), Some(&"state1".to_string()));
    }

    #[test]
    fn test_state_change_serialization() {
        let mut changed = HashMap::new();
        changed.insert("Email".to_string(), "state123".to_string());
        changed.insert("Mailbox".to_string(), "state456".to_string());

        let state_change = StateChange { changed };

        let json = serde_json::to_string(&state_change).unwrap();
        assert!(json.contains("Email"));
        assert!(json.contains("state123"));
    }

    #[test]
    fn test_push_subscription_serialization() {
        let subscription = EventSourcePushHint {
            url: "https://push.example.com/abc123".to_string(),
            types: Some(vec!["Email".to_string(), "Mailbox".to_string()]),
        };

        let json = serde_json::to_string(&subscription).unwrap();
        assert!(json.contains("push.example.com"));
    }

    #[test]
    fn test_event_source_manager_default() {
        let manager = EventSourceManager::default();
        assert!(manager.get_state("any").is_none());
    }

    #[test]
    fn test_event_source_manager_clone() {
        let manager1 = EventSourceManager::new();
        manager1.notify_change("Email".to_string(), "state1".to_string());

        let manager2 = manager1.clone();
        assert_eq!(manager2.get_state("Email"), Some("state1".to_string()));
    }

    #[test]
    fn test_get_nonexistent_state() {
        let manager = EventSourceManager::new();
        assert_eq!(manager.get_state("NonExistent"), None);
    }

    #[test]
    fn test_notify_empty_state() {
        let manager = EventSourceManager::new();
        manager.notify_change("Email".to_string(), "".to_string());

        assert_eq!(manager.get_state("Email"), Some("".to_string()));
    }

    #[test]
    fn test_subscribe_before_notify() {
        let manager = EventSourceManager::new();
        let mut rx = manager.subscribe();

        // No changes yet
        assert!(rx.try_recv().is_err());

        manager.notify_change("Email".to_string(), "state1".to_string());

        // Now should receive
        assert!(rx.try_recv().is_ok());
    }

    #[test]
    fn test_subscribe_after_notify() {
        let manager = EventSourceManager::new();

        manager.notify_change("Email".to_string(), "state1".to_string());

        // Subscribe after notification
        let mut rx = manager.subscribe();

        // Won't receive past notifications
        assert!(rx.try_recv().is_err());

        // But state is still accessible
        assert_eq!(manager.get_state("Email"), Some("state1".to_string()));
    }

    #[test]
    fn test_multiple_data_types() {
        let manager = EventSourceManager::new();

        manager.notify_change("Email".to_string(), "email_state".to_string());
        manager.notify_change("Mailbox".to_string(), "mailbox_state".to_string());
        manager.notify_change("Thread".to_string(), "thread_state".to_string());
        manager.notify_change("Identity".to_string(), "identity_state".to_string());

        assert_eq!(manager.get_state("Email"), Some("email_state".to_string()));
        assert_eq!(
            manager.get_state("Mailbox"),
            Some("mailbox_state".to_string())
        );
        assert_eq!(
            manager.get_state("Thread"),
            Some("thread_state".to_string())
        );
        assert_eq!(
            manager.get_state("Identity"),
            Some("identity_state".to_string())
        );
    }

    #[test]
    fn test_state_change_empty_changed() {
        let state_change = StateChange {
            changed: HashMap::new(),
        };

        let json = serde_json::to_string(&state_change).unwrap();
        assert!(json.contains("changed"));
    }

    #[test]
    fn test_push_subscription_without_types() {
        let subscription = EventSourcePushHint {
            url: "https://push.example.com/def456".to_string(),
            types: None,
        };

        let json = serde_json::to_string(&subscription).unwrap();
        assert!(!json.contains("types"));
    }

    #[test]
    fn test_concurrent_notifications() {
        let manager = EventSourceManager::new();
        let mut rx = manager.subscribe();

        // Send multiple notifications quickly
        for i in 0..10 {
            manager.notify_change(format!("Type{}", i), format!("state{}", i));
        }

        // Should receive all (or most, depending on timing)
        let mut received = 0;
        while rx.try_recv().is_ok() {
            received += 1;
        }

        assert!(received > 0);
    }

    #[test]
    fn test_state_persistence_across_notifications() {
        let manager = EventSourceManager::new();

        manager.notify_change("Email".to_string(), "state1".to_string());
        manager.notify_change("Mailbox".to_string(), "state2".to_string());

        // Update Email again
        manager.notify_change("Email".to_string(), "state3".to_string());

        // Email should have new state, Mailbox unchanged
        assert_eq!(manager.get_state("Email"), Some("state3".to_string()));
        assert_eq!(manager.get_state("Mailbox"), Some("state2".to_string()));
    }

    #[test]
    fn test_subscriber_receives_only_new_changes() {
        let manager = EventSourceManager::new();

        manager.notify_change("Email".to_string(), "old_state".to_string());

        let mut rx = manager.subscribe();

        manager.notify_change("Email".to_string(), "new_state".to_string());

        let change = rx.try_recv().unwrap();
        assert_eq!(change.changed.get("Email"), Some(&"new_state".to_string()));
    }

    #[test]
    fn test_broadcast_channel_capacity() {
        let manager = EventSourceManager::new();
        let mut rx = manager.subscribe();

        // Send more than channel capacity
        for i in 0..200 {
            manager.notify_change(format!("Type{}", i), format!("state{}", i));
        }

        // Receiver might lag
        let mut received = 0;
        let mut lagged = false;
        loop {
            match rx.try_recv() {
                Ok(_) => received += 1,
                Err(broadcast::error::TryRecvError::Lagged(_)) => {
                    // Expected when overwhelmed
                    lagged = true;
                    break;
                }
                Err(_) => break,
            }
        }

        // Either we received some messages or we lagged (which means channel was full)
        assert!(received > 0 || lagged);
    }

    #[test]
    fn test_state_change_deserialization() {
        let json = r#"{"changed":{"Email":"state1","Mailbox":"state2"}}"#;
        let state_change: StateChange = serde_json::from_str(json).unwrap();

        assert_eq!(
            state_change.changed.get("Email"),
            Some(&"state1".to_string())
        );
        assert_eq!(
            state_change.changed.get("Mailbox"),
            Some(&"state2".to_string())
        );
    }

    #[test]
    fn test_push_subscription_deserialization() {
        let json = r#"{"url":"https://example.com","types":["Email"]}"#;
        let subscription: EventSourcePushHint = serde_json::from_str(json).unwrap();

        assert_eq!(subscription.url, "https://example.com");
        assert_eq!(subscription.types, Some(vec!["Email".to_string()]));
    }
}