pandrs 0.3.0

A high-performance DataFrame library for Rust, providing pandas-like API with advanced features including SIMD optimization, parallel processing, and distributed computing capabilities
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
//! Session Management
//!
//! This module provides session management for authenticated users,
//! including session creation, validation, refresh, and expiration.

use crate::multitenancy::TenantId;
use std::collections::HashMap;
use std::time::{Duration, Instant, SystemTime};

/// User session information
#[derive(Debug, Clone)]
pub struct Session {
    /// Unique session identifier
    pub session_id: String,
    /// Associated user ID
    pub user_id: String,
    /// Associated tenant ID
    pub tenant_id: TenantId,
    /// Session creation time
    pub created_at: SystemTime,
    /// Last activity time
    pub last_activity: Instant,
    /// Session timeout duration
    pub timeout: Duration,
    /// Session data/attributes
    pub attributes: HashMap<String, String>,
    /// IP address (if available)
    pub ip_address: Option<String>,
    /// User agent (if available)
    pub user_agent: Option<String>,
    /// Whether the session is active
    pub active: bool,
}

impl Session {
    /// Create a new session
    pub fn new(user_id: impl Into<String>, tenant_id: impl Into<String>) -> Self {
        Session {
            session_id: generate_session_id(),
            user_id: user_id.into(),
            tenant_id: tenant_id.into(),
            created_at: SystemTime::now(),
            last_activity: Instant::now(),
            timeout: Duration::from_secs(3600), // Default 1 hour
            attributes: HashMap::new(),
            ip_address: None,
            user_agent: None,
            active: true,
        }
    }

    /// Set session timeout
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Set IP address
    pub fn with_ip_address(mut self, ip: impl Into<String>) -> Self {
        self.ip_address = Some(ip.into());
        self
    }

    /// Set user agent
    pub fn with_user_agent(mut self, ua: impl Into<String>) -> Self {
        self.user_agent = Some(ua.into());
        self
    }

    /// Set a session attribute
    pub fn set_attribute(&mut self, key: impl Into<String>, value: impl Into<String>) {
        self.attributes.insert(key.into(), value.into());
    }

    /// Get a session attribute
    pub fn get_attribute(&self, key: &str) -> Option<&String> {
        self.attributes.get(key)
    }

    /// Remove a session attribute
    pub fn remove_attribute(&mut self, key: &str) -> Option<String> {
        self.attributes.remove(key)
    }

    /// Check if the session has expired
    pub fn is_expired(&self) -> bool {
        !self.active || self.last_activity.elapsed() > self.timeout
    }

    /// Refresh the session (update last activity time)
    pub fn refresh(&mut self) {
        self.last_activity = Instant::now();
    }

    /// Get remaining time before expiration
    pub fn time_remaining(&self) -> Duration {
        if self.is_expired() {
            Duration::ZERO
        } else {
            self.timeout.saturating_sub(self.last_activity.elapsed())
        }
    }

    /// Invalidate the session
    pub fn invalidate(&mut self) {
        self.active = false;
    }

    /// Get session duration
    pub fn duration(&self) -> Duration {
        self.created_at.elapsed().unwrap_or(Duration::ZERO)
    }
}

/// Session store for managing multiple sessions
#[derive(Debug)]
pub struct SessionStore {
    /// Active sessions by ID
    sessions: HashMap<String, Session>,
    /// Sessions by user ID
    user_sessions: HashMap<String, Vec<String>>,
    /// Maximum sessions per user
    max_sessions_per_user: usize,
    /// Default session timeout
    default_timeout: Duration,
    /// Whether to allow concurrent sessions
    allow_concurrent: bool,
}

impl SessionStore {
    /// Create a new session store
    pub fn new() -> Self {
        SessionStore {
            sessions: HashMap::new(),
            user_sessions: HashMap::new(),
            max_sessions_per_user: 5,
            default_timeout: Duration::from_secs(3600),
            allow_concurrent: true,
        }
    }

    /// Set maximum sessions per user
    pub fn with_max_sessions(mut self, max: usize) -> Self {
        self.max_sessions_per_user = max;
        self
    }

    /// Set default session timeout
    pub fn with_default_timeout(mut self, timeout: Duration) -> Self {
        self.default_timeout = timeout;
        self
    }

    /// Disable concurrent sessions
    pub fn without_concurrent_sessions(mut self) -> Self {
        self.allow_concurrent = false;
        self
    }

    /// Create a new session for a user
    pub fn create_session(&mut self, user_id: &str, tenant_id: &str) -> Session {
        // If concurrent sessions not allowed, invalidate existing sessions
        if !self.allow_concurrent {
            self.invalidate_user_sessions(user_id);
        }

        // Check if user has reached max sessions
        if let Some(session_ids) = self.user_sessions.get(user_id) {
            if session_ids.len() >= self.max_sessions_per_user {
                // Remove oldest session
                if let Some(oldest_id) = session_ids.first().cloned() {
                    self.remove_session(&oldest_id);
                }
            }
        }

        let session = Session::new(user_id, tenant_id).with_timeout(self.default_timeout);

        let session_id = session.session_id.clone();

        self.sessions.insert(session_id.clone(), session.clone());

        self.user_sessions
            .entry(user_id.to_string())
            .or_insert_with(Vec::new)
            .push(session_id);

        session
    }

    /// Get a session by ID
    pub fn get_session(&self, session_id: &str) -> Option<&Session> {
        self.sessions.get(session_id)
    }

    /// Get a mutable reference to a session
    pub fn get_session_mut(&mut self, session_id: &str) -> Option<&mut Session> {
        self.sessions.get_mut(session_id)
    }

    /// Validate and refresh a session
    pub fn validate_session(&mut self, session_id: &str) -> Option<&Session> {
        if let Some(session) = self.sessions.get_mut(session_id) {
            if session.is_expired() {
                return None;
            }
            session.refresh();
            return self.sessions.get(session_id);
        }
        None
    }

    /// Remove a session
    pub fn remove_session(&mut self, session_id: &str) -> Option<Session> {
        if let Some(session) = self.sessions.remove(session_id) {
            // Remove from user_sessions
            if let Some(session_ids) = self.user_sessions.get_mut(&session.user_id) {
                session_ids.retain(|id| id != session_id);
            }
            return Some(session);
        }
        None
    }

    /// Invalidate all sessions for a user
    pub fn invalidate_user_sessions(&mut self, user_id: &str) {
        if let Some(session_ids) = self.user_sessions.get(user_id) {
            for session_id in session_ids.clone() {
                if let Some(session) = self.sessions.get_mut(&session_id) {
                    session.invalidate();
                }
            }
        }
    }

    /// Get all sessions for a user
    pub fn get_user_sessions(&self, user_id: &str) -> Vec<&Session> {
        self.user_sessions
            .get(user_id)
            .map(|session_ids| {
                session_ids
                    .iter()
                    .filter_map(|id| self.sessions.get(id))
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Get active session count for a user
    pub fn get_active_session_count(&self, user_id: &str) -> usize {
        self.get_user_sessions(user_id)
            .iter()
            .filter(|s| !s.is_expired())
            .count()
    }

    /// Clean up expired sessions
    pub fn cleanup_expired(&mut self) {
        let expired_ids: Vec<String> = self
            .sessions
            .iter()
            .filter(|(_, session)| session.is_expired())
            .map(|(id, _)| id.clone())
            .collect();

        for session_id in expired_ids {
            self.remove_session(&session_id);
        }
    }

    /// Get total session count
    pub fn session_count(&self) -> usize {
        self.sessions.len()
    }

    /// Get active session count
    pub fn active_session_count(&self) -> usize {
        self.sessions.values().filter(|s| !s.is_expired()).count()
    }
}

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

/// Session-based authentication context
#[derive(Debug, Clone)]
pub struct SessionContext {
    /// Current session
    pub session: Session,
    /// Authenticated user ID
    pub user_id: String,
    /// Tenant ID
    pub tenant_id: TenantId,
    /// Request-specific data
    pub request_data: HashMap<String, String>,
}

impl SessionContext {
    /// Create from a session
    pub fn from_session(session: Session) -> Self {
        SessionContext {
            user_id: session.user_id.clone(),
            tenant_id: session.tenant_id.clone(),
            session,
            request_data: HashMap::new(),
        }
    }

    /// Set request data
    pub fn set_request_data(&mut self, key: impl Into<String>, value: impl Into<String>) {
        self.request_data.insert(key.into(), value.into());
    }

    /// Get request data
    pub fn get_request_data(&self, key: &str) -> Option<&String> {
        self.request_data.get(key)
    }
}

// Helper functions

/// Generate a unique session ID
fn generate_session_id() -> String {
    use rand::Rng;
    let mut bytes = [0u8; 32];
    rand::rng().fill_bytes(&mut bytes);
    format!(
        "sess_{}",
        bytes
            .iter()
            .map(|b| format!("{:02x}", b))
            .collect::<String>()
    )
}

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

    #[test]
    fn test_session_creation() {
        let session = Session::new("user1", "tenant_a");

        assert!(session.session_id.starts_with("sess_"));
        assert_eq!(session.user_id, "user1");
        assert_eq!(session.tenant_id, "tenant_a");
        assert!(session.active);
        assert!(!session.is_expired());
    }

    #[test]
    fn test_session_expiration() {
        let session = Session::new("user1", "tenant_a").with_timeout(Duration::from_millis(1));

        // Wait for session to expire
        std::thread::sleep(Duration::from_millis(10));

        assert!(session.is_expired());
    }

    #[test]
    fn test_session_refresh() {
        let mut session = Session::new("user1", "tenant_a").with_timeout(Duration::from_secs(1));

        // Wait a bit
        std::thread::sleep(Duration::from_millis(100));

        let time_before_refresh = session.time_remaining();

        // Refresh session
        session.refresh();

        let time_after_refresh = session.time_remaining();

        // Time remaining should be reset
        assert!(time_after_refresh > time_before_refresh);
    }

    #[test]
    fn test_session_attributes() {
        let mut session = Session::new("user1", "tenant_a");

        session.set_attribute("theme", "dark");
        session.set_attribute("language", "en");

        assert_eq!(session.get_attribute("theme"), Some(&"dark".to_string()));
        assert_eq!(session.get_attribute("language"), Some(&"en".to_string()));
        assert_eq!(session.get_attribute("missing"), None);

        // Remove attribute
        let removed = session.remove_attribute("theme");
        assert_eq!(removed, Some("dark".to_string()));
        assert_eq!(session.get_attribute("theme"), None);
    }

    #[test]
    fn test_session_store() {
        let mut store = SessionStore::new();

        // Create session
        let session = store.create_session("user1", "tenant_a");
        let session_id = session.session_id.clone();

        // Get session
        assert!(store.get_session(&session_id).is_some());

        // Validate session
        assert!(store.validate_session(&session_id).is_some());

        // Remove session
        let removed = store.remove_session(&session_id);
        assert!(removed.is_some());
        assert!(store.get_session(&session_id).is_none());
    }

    #[test]
    fn test_session_store_max_sessions() {
        let mut store = SessionStore::new().with_max_sessions(2);

        // Create 3 sessions for the same user
        let s1 = store.create_session("user1", "tenant_a");
        let s2 = store.create_session("user1", "tenant_a");
        let s3 = store.create_session("user1", "tenant_a");

        // First session should be removed
        assert!(store.get_session(&s1.session_id).is_none());
        assert!(store.get_session(&s2.session_id).is_some());
        assert!(store.get_session(&s3.session_id).is_some());
    }

    #[test]
    fn test_session_store_no_concurrent() {
        let mut store = SessionStore::new().without_concurrent_sessions();

        // Create first session
        let s1 = store.create_session("user1", "tenant_a");

        // Create second session (should invalidate first)
        let s2 = store.create_session("user1", "tenant_a");

        // First session should be invalidated
        let session1 = store.get_session(&s1.session_id);
        assert!(session1.is_none() || !session1.expect("operation should succeed").active);

        // Second session should be active
        assert!(store.get_session(&s2.session_id).is_some());
    }

    #[test]
    fn test_session_store_cleanup() {
        let mut store = SessionStore::new().with_default_timeout(Duration::from_millis(1));

        // Create sessions
        store.create_session("user1", "tenant_a");
        store.create_session("user2", "tenant_b");

        // Wait for expiration
        std::thread::sleep(Duration::from_millis(10));

        // Cleanup
        store.cleanup_expired();

        assert_eq!(store.session_count(), 0);
    }

    #[test]
    fn test_user_sessions() {
        let mut store = SessionStore::new();

        store.create_session("user1", "tenant_a");
        store.create_session("user1", "tenant_a");
        store.create_session("user2", "tenant_b");

        assert_eq!(store.get_user_sessions("user1").len(), 2);
        assert_eq!(store.get_user_sessions("user2").len(), 1);
        assert_eq!(store.get_active_session_count("user1"), 2);
    }

    #[test]
    fn test_session_context() {
        let session = Session::new("user1", "tenant_a");
        let mut ctx = SessionContext::from_session(session);

        assert_eq!(ctx.user_id, "user1");
        assert_eq!(ctx.tenant_id, "tenant_a");

        ctx.set_request_data("correlation_id", "abc123");
        assert_eq!(
            ctx.get_request_data("correlation_id"),
            Some(&"abc123".to_string())
        );
    }
}