axon-lang 1.38.1

AXON v1.5.1 — first crates.io publication of the AXON language full-stack runtime. Lexer/parser/type-checker/IR generator (re-exported from axon-frontend) plus the native Rust runtime: typed channels (TypedEventBus with QoS×5, π-calculus mobility, capability extrusion via shield D8 — Fase 13.f.2), Free Monad CPS handlers (Fase 2), lease kernel + reconcile loop (Fase 3+5), Epistemic Security Kernel (ESK Fase 6), Trust Types + ReplayLog (Fase 11.a+11.c), Stateful PEM over WebSocket (Fase 11.d), Ontological Tool Synthesis (Fase 11.e), Mobile Typed Channels (Fase 13). Crate publishes as `axon-lang` to mirror the Python PyPI package; library import remains `use axon::*` so existing call sites keep working unchanged.
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
//! Request Logger — structured audit log for AxonServer API requests.
//!
//! Records each API request as a structured `RequestLogEntry` with:
//!   - method, path, status code, latency
//!   - client key (from auth token or "anonymous")
//!   - timestamp (monotonic + wall clock)
//!
//! The log is an in-memory ring buffer with configurable capacity.
//! Entries can be queried by path, status, or time range.
//!
//! Endpoints:
//!   - `GET /v1/logs` — query recent request logs
//!   - `GET /v1/logs/stats` — aggregate request statistics

use std::collections::VecDeque;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use serde::Serialize;

// ── Entry ────────────────────────────────────────────────────────────────

/// A single request log entry.
#[derive(Debug, Clone, Serialize)]
pub struct RequestLogEntry {
    /// Wall-clock timestamp (Unix seconds).
    pub timestamp: u64,
    /// HTTP method (GET, POST, DELETE).
    pub method: String,
    /// Request path (e.g., "/v1/deploy").
    pub path: String,
    /// HTTP status code.
    pub status: u16,
    /// Request latency in microseconds.
    pub latency_us: u64,
    /// Client identifier (auth token or "anonymous").
    pub client_key: String,
}

// ── Config ───────────────────────────────────────────────────────────────

/// Request logger configuration.
#[derive(Debug, Clone)]
pub struct RequestLogConfig {
    /// Maximum entries in the ring buffer.
    pub capacity: usize,
    /// Whether logging is enabled.
    pub enabled: bool,
}

impl RequestLogConfig {
    /// Default: 1000 entries, enabled.
    pub fn default_config() -> Self {
        RequestLogConfig {
            capacity: 1000,
            enabled: true,
        }
    }

    /// Disabled logger.
    pub fn disabled() -> Self {
        RequestLogConfig {
            capacity: 0,
            enabled: false,
        }
    }
}

// ── Logger ───────────────────────────────────────────────────────────────

/// In-memory ring buffer request logger.
pub struct RequestLogger {
    config: RequestLogConfig,
    entries: VecDeque<RequestLogEntry>,
    started_at: Instant,
    total_requests: u64,
    total_errors: u64,
}

impl RequestLogger {
    /// Create a new request logger.
    pub fn new(config: RequestLogConfig) -> Self {
        RequestLogger {
            entries: VecDeque::with_capacity(config.capacity.min(1024)),
            config,
            started_at: Instant::now(),
            total_requests: 0,
            total_errors: 0,
        }
    }

    /// Record a request.
    pub fn record(&mut self, method: &str, path: &str, status: u16, latency: Duration, client_key: &str) {
        if !self.config.enabled {
            return;
        }

        self.total_requests += 1;
        if status >= 400 {
            self.total_errors += 1;
        }

        let entry = RequestLogEntry {
            timestamp: wall_clock_secs(),
            method: method.to_string(),
            path: path.to_string(),
            status,
            latency_us: latency.as_micros() as u64,
            client_key: client_key.to_string(),
        };

        if self.entries.len() >= self.config.capacity && self.config.capacity > 0 {
            self.entries.pop_front();
        }
        if self.config.capacity > 0 {
            self.entries.push_back(entry);
        }
    }

    /// Get the configuration.
    pub fn config(&self) -> &RequestLogConfig {
        &self.config
    }

    /// Update the configuration at runtime.
    pub fn update_config(&mut self, capacity: Option<usize>, enabled: Option<bool>) {
        if let Some(cap) = capacity {
            self.config.capacity = cap;
            // Trim entries if new capacity is smaller
            while self.entries.len() > cap {
                self.entries.pop_front();
            }
        }
        if let Some(en) = enabled {
            self.config.enabled = en;
        }
    }

    /// Get recent entries (newest first), optionally filtered.
    pub fn recent(&self, limit: usize, filter: Option<&LogFilter>) -> Vec<&RequestLogEntry> {
        let result: Vec<&RequestLogEntry> = self.entries.iter().rev()
            .filter(|e| match filter {
                Some(f) => f.matches(e),
                None => true,
            })
            .take(limit)
            .collect();
        // Already newest-first from rev()
        result
    }

    /// Compute aggregate statistics.
    pub fn stats(&self) -> LogStats {
        let entries: Vec<&RequestLogEntry> = self.entries.iter().collect();

        let mut path_counts: std::collections::HashMap<String, u64> = std::collections::HashMap::new();
        let mut status_counts: std::collections::HashMap<u16, u64> = std::collections::HashMap::new();
        let mut total_latency_us: u64 = 0;
        let mut max_latency_us: u64 = 0;

        for e in &entries {
            *path_counts.entry(e.path.clone()).or_insert(0) += 1;
            *status_counts.entry(e.status).or_insert(0) += 1;
            total_latency_us += e.latency_us;
            if e.latency_us > max_latency_us {
                max_latency_us = e.latency_us;
            }
        }

        let avg_latency_us = if entries.is_empty() {
            0
        } else {
            total_latency_us / entries.len() as u64
        };

        let mut top_paths: Vec<(String, u64)> = path_counts.into_iter().collect();
        top_paths.sort_by(|a, b| b.1.cmp(&a.1));
        top_paths.truncate(10);

        let mut status_breakdown: Vec<(u16, u64)> = status_counts.into_iter().collect();
        status_breakdown.sort_by_key(|(k, _)| *k);

        LogStats {
            total_requests: self.total_requests,
            total_errors: self.total_errors,
            buffered_entries: self.entries.len(),
            avg_latency_us,
            max_latency_us,
            top_paths,
            status_breakdown,
            uptime_secs: self.started_at.elapsed().as_secs(),
        }
    }

    /// Number of buffered entries.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Whether the buffer is empty.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Total requests recorded (including evicted).
    pub fn total_requests(&self) -> u64 {
        self.total_requests
    }

    /// Clear all entries.
    pub fn clear(&mut self) {
        self.entries.clear();
    }
}

// ── Filter ───────────────────────────────────────────────────────────────

/// Filter for querying log entries.
#[derive(Debug, Clone, Default, Serialize)]
pub struct LogFilter {
    /// Filter by path prefix (e.g., "/v1/deploy").
    pub path_prefix: Option<String>,
    /// Filter by minimum status code.
    pub min_status: Option<u16>,
    /// Filter by maximum status code.
    pub max_status: Option<u16>,
    /// Filter by client key.
    pub client_key: Option<String>,
}

impl LogFilter {
    /// Check if an entry matches this filter.
    pub fn matches(&self, entry: &RequestLogEntry) -> bool {
        if let Some(ref prefix) = self.path_prefix {
            if !entry.path.starts_with(prefix) {
                return false;
            }
        }
        if let Some(min) = self.min_status {
            if entry.status < min {
                return false;
            }
        }
        if let Some(max) = self.max_status {
            if entry.status > max {
                return false;
            }
        }
        if let Some(ref key) = self.client_key {
            if entry.client_key != *key {
                return false;
            }
        }
        true
    }
}

// ── Stats ────────────────────────────────────────────────────────────────

/// Aggregate request statistics.
#[derive(Debug, Clone, Serialize)]
pub struct LogStats {
    pub total_requests: u64,
    pub total_errors: u64,
    pub buffered_entries: usize,
    pub avg_latency_us: u64,
    pub max_latency_us: u64,
    pub top_paths: Vec<(String, u64)>,
    pub status_breakdown: Vec<(u16, u64)>,
    pub uptime_secs: u64,
}

// ── Helpers ──────────────────────────────────────────────────────────────

fn wall_clock_secs() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
}

// ── Tests ────────────────────────────────────────────────────────────────

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

    #[test]
    fn record_and_retrieve() {
        let mut logger = RequestLogger::new(RequestLogConfig::default_config());
        logger.record("GET", "/v1/health", 200, Duration::from_micros(500), "anon");
        logger.record("POST", "/v1/deploy", 200, Duration::from_micros(1500), "token_a");

        assert_eq!(logger.len(), 2);
        assert_eq!(logger.total_requests(), 2);

        let recent = logger.recent(10, None);
        assert_eq!(recent.len(), 2);
        // Newest first
        assert_eq!(recent[0].path, "/v1/deploy");
        assert_eq!(recent[1].path, "/v1/health");
    }

    #[test]
    fn ring_buffer_eviction() {
        let config = RequestLogConfig { capacity: 3, enabled: true };
        let mut logger = RequestLogger::new(config);

        for i in 0..5 {
            logger.record("GET", &format!("/v1/req{}", i), 200, Duration::from_micros(100), "c");
        }

        assert_eq!(logger.len(), 3);
        assert_eq!(logger.total_requests(), 5);

        let recent = logger.recent(10, None);
        assert_eq!(recent[0].path, "/v1/req4");
        assert_eq!(recent[2].path, "/v1/req2");
    }

    #[test]
    fn disabled_logger_no_recording() {
        let mut logger = RequestLogger::new(RequestLogConfig::disabled());
        logger.record("GET", "/v1/health", 200, Duration::from_micros(100), "c");
        assert_eq!(logger.len(), 0);
        assert_eq!(logger.total_requests(), 0);
    }

    #[test]
    fn error_counting() {
        let mut logger = RequestLogger::new(RequestLogConfig::default_config());
        logger.record("GET", "/v1/a", 200, Duration::from_micros(100), "c");
        logger.record("GET", "/v1/b", 401, Duration::from_micros(100), "c");
        logger.record("GET", "/v1/c", 500, Duration::from_micros(100), "c");
        logger.record("GET", "/v1/d", 429, Duration::from_micros(100), "c");

        let stats = logger.stats();
        assert_eq!(stats.total_requests, 4);
        assert_eq!(stats.total_errors, 3); // 401, 500, 429
    }

    #[test]
    fn filter_by_path_prefix() {
        let mut logger = RequestLogger::new(RequestLogConfig::default_config());
        logger.record("GET", "/v1/health", 200, Duration::from_micros(100), "c");
        logger.record("POST", "/v1/deploy", 200, Duration::from_micros(100), "c");
        logger.record("GET", "/v1/health/live", 200, Duration::from_micros(100), "c");

        let filter = LogFilter { path_prefix: Some("/v1/health".into()), ..Default::default() };
        let result = logger.recent(10, Some(&filter));
        assert_eq!(result.len(), 2);
    }

    #[test]
    fn filter_by_status_range() {
        let mut logger = RequestLogger::new(RequestLogConfig::default_config());
        logger.record("GET", "/v1/a", 200, Duration::from_micros(100), "c");
        logger.record("GET", "/v1/b", 401, Duration::from_micros(100), "c");
        logger.record("GET", "/v1/c", 500, Duration::from_micros(100), "c");

        let filter = LogFilter { min_status: Some(400), ..Default::default() };
        let result = logger.recent(10, Some(&filter));
        assert_eq!(result.len(), 2);
    }

    #[test]
    fn filter_by_client_key() {
        let mut logger = RequestLogger::new(RequestLogConfig::default_config());
        logger.record("GET", "/v1/a", 200, Duration::from_micros(100), "alice");
        logger.record("GET", "/v1/b", 200, Duration::from_micros(100), "bob");
        logger.record("GET", "/v1/c", 200, Duration::from_micros(100), "alice");

        let filter = LogFilter { client_key: Some("alice".into()), ..Default::default() };
        let result = logger.recent(10, Some(&filter));
        assert_eq!(result.len(), 2);
    }

    #[test]
    fn stats_computation() {
        let mut logger = RequestLogger::new(RequestLogConfig::default_config());
        logger.record("GET", "/v1/health", 200, Duration::from_micros(100), "c");
        logger.record("GET", "/v1/health", 200, Duration::from_micros(300), "c");
        logger.record("POST", "/v1/deploy", 200, Duration::from_micros(500), "c");

        let stats = logger.stats();
        assert_eq!(stats.total_requests, 3);
        assert_eq!(stats.total_errors, 0);
        assert_eq!(stats.buffered_entries, 3);
        assert_eq!(stats.avg_latency_us, 300); // (100+300+500)/3
        assert_eq!(stats.max_latency_us, 500);
        assert_eq!(stats.top_paths[0].0, "/v1/health");
        assert_eq!(stats.top_paths[0].1, 2);
    }

    #[test]
    fn stats_empty_logger() {
        let logger = RequestLogger::new(RequestLogConfig::default_config());
        let stats = logger.stats();
        assert_eq!(stats.total_requests, 0);
        assert_eq!(stats.avg_latency_us, 0);
        assert_eq!(stats.max_latency_us, 0);
    }

    #[test]
    fn clear_entries() {
        let mut logger = RequestLogger::new(RequestLogConfig::default_config());
        logger.record("GET", "/v1/a", 200, Duration::from_micros(100), "c");
        logger.record("GET", "/v1/b", 200, Duration::from_micros(100), "c");
        assert_eq!(logger.len(), 2);

        logger.clear();
        assert_eq!(logger.len(), 0);
        assert!(logger.is_empty());
        // total_requests preserved
        assert_eq!(logger.total_requests(), 2);
    }

    #[test]
    fn entry_serializes_to_json() {
        let entry = RequestLogEntry {
            timestamp: 1700000000,
            method: "POST".into(),
            path: "/v1/deploy".into(),
            status: 200,
            latency_us: 1500,
            client_key: "token_abc".into(),
        };
        let json = serde_json::to_string(&entry).unwrap();
        assert!(json.contains("\"method\":\"POST\""));
        assert!(json.contains("\"path\":\"/v1/deploy\""));
        assert!(json.contains("\"status\":200"));
        assert!(json.contains("\"latency_us\":1500"));
    }

    #[test]
    fn stats_serializes_to_json() {
        let stats = LogStats {
            total_requests: 100,
            total_errors: 5,
            buffered_entries: 50,
            avg_latency_us: 250,
            max_latency_us: 5000,
            top_paths: vec![("/v1/health".into(), 40)],
            status_breakdown: vec![(200, 95), (500, 5)],
            uptime_secs: 3600,
        };
        let json = serde_json::to_string(&stats).unwrap();
        assert!(json.contains("\"total_requests\":100"));
        assert!(json.contains("\"total_errors\":5"));
    }

    #[test]
    fn recent_with_limit() {
        let mut logger = RequestLogger::new(RequestLogConfig::default_config());
        for i in 0..10 {
            logger.record("GET", &format!("/v1/r{}", i), 200, Duration::from_micros(100), "c");
        }
        let recent = logger.recent(3, None);
        assert_eq!(recent.len(), 3);
        assert_eq!(recent[0].path, "/v1/r9");
    }

    #[test]
    fn combined_filter() {
        let mut logger = RequestLogger::new(RequestLogConfig::default_config());
        logger.record("POST", "/v1/deploy", 200, Duration::from_micros(100), "alice");
        logger.record("POST", "/v1/deploy", 500, Duration::from_micros(100), "alice");
        logger.record("POST", "/v1/deploy", 200, Duration::from_micros(100), "bob");
        logger.record("GET", "/v1/health", 200, Duration::from_micros(100), "alice");

        let filter = LogFilter {
            path_prefix: Some("/v1/deploy".into()),
            client_key: Some("alice".into()),
            min_status: Some(200),
            max_status: Some(299),
        };
        let result = logger.recent(10, Some(&filter));
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].status, 200);
    }

    #[test]
    fn default_config_values() {
        let cfg = RequestLogConfig::default_config();
        assert_eq!(cfg.capacity, 1000);
        assert!(cfg.enabled);
    }

    #[test]
    fn timestamp_is_recent() {
        let mut logger = RequestLogger::new(RequestLogConfig::default_config());
        logger.record("GET", "/v1/a", 200, Duration::from_micros(100), "c");
        let recent = logger.recent(1, None);
        assert!(recent[0].timestamp > 1700000000);
    }
}