cedarling 0.0.58

The Cedarling: a high-performance local authorization service powered by the Rust Cedar Engine.
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
// This software is available under the Apache-2.0 license.
// See https://www.apache.org/licenses/LICENSE-2.0.txt for full text.
//
// Copyright (c) 2024, Gluu, Inc.

//! Implements a logger that writes to standard output (stdout).
//! Write failures are silently ignored to prevent panics in logging code paths.

use std::io::Write;
use std::sync::mpsc;
use std::sync::{Arc, Mutex};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};

use crate::log::LogLevel;
use crate::log::err_log_entry::ErrorLogEntry;
use crate::log::interface::{LogWriter, Loggable};

/// Mode for stdout logger in native builds.
/// Supports both immediate and asynchronous logging.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum StdOutLoggerMode {
    /// Immediate synchronous logging (no buffering).
    Immediate,
    /// Asynchronous logging with configurable timeout and buffer.
    Async {
        /// Timeout in milliseconds to flush the log buffer.
        timeout_millis: u64,
        /// Maximum buffer size in bytes before an automatic flush.
        buffer_limit: usize,
    },
}

impl StdOutLoggerMode {
    /// 100 ms default timeout
    pub const DEFAULT_FLUSH_TIMEOUT_MILLIS: u64 = 100;
    /// 1 MB limit
    pub const DEFAULT_BUFFER_LIMIT: usize = 1 << 20;
}

enum LogMessage {
    Log(Box<dyn FnOnce() -> String + Send + 'static>),
    Shutdown,
}

fn spawn_writer_thread(
    receiver: mpsc::Receiver<LogMessage>,
    writer: Box<dyn Write + Send + Sync>,
    flush_timeout: Duration,
    buffer_limit: usize,
) -> JoinHandle<()> {
    thread::spawn(move || {
        let mut writer = writer;
        let mut buffer = String::new();
        let mut next_flush_deadline = Instant::now() + flush_timeout;
        loop {
            // Check if flush deadline has passed
            let now = Instant::now();
            if now >= next_flush_deadline && !buffer.is_empty() {
                let _ = writer.write_all(buffer.as_bytes());
                buffer.clear();
                next_flush_deadline = now + flush_timeout;
            }

            // Compute remaining time until next flush deadline
            let remaining = next_flush_deadline.saturating_duration_since(now);
            match receiver.recv_timeout(remaining) {
                Ok(LogMessage::Log(serializer)) => {
                    let json_string = serializer();
                    buffer.push_str(&json_string);
                    buffer.push('\n');
                    if buffer.len() >= buffer_limit {
                        let _ = writer.write_all(buffer.as_bytes());
                        buffer.clear();
                        // Reset flush deadline since we just flushed
                        next_flush_deadline = Instant::now() + flush_timeout;
                    }
                },
                Ok(LogMessage::Shutdown) => {
                    break;
                },
                Err(mpsc::RecvTimeoutError::Timeout) => {
                    // Timeout, flush buffer if not empty
                    if !buffer.is_empty() {
                        let _ = writer.write_all(buffer.as_bytes());
                        buffer.clear();
                        next_flush_deadline = Instant::now() + flush_timeout;
                    }
                },
                Err(mpsc::RecvTimeoutError::Disconnected) => {
                    // Sender dropped, flush and exit
                    if !buffer.is_empty() {
                        let _ = writer.write_all(buffer.as_bytes());
                        buffer.clear();
                    }
                    break;
                },
            }
        }
        // Final flush
        if !buffer.is_empty() {
            let _ = writer.write_all(buffer.as_bytes());
        }
    })
}

/// A logger that write to std output.
pub(crate) struct StdOutLogger {
    mode: StdOutLoggerMode,
    sender: Option<mpsc::Sender<LogMessage>>,
    thread_handle: Option<JoinHandle<()>>,
    writer: Option<Arc<Mutex<Box<dyn Write + Send + Sync>>>>,
    log_level: LogLevel,
}

impl StdOutLogger {
    // is used as fallback in memory logger, so default is immediate mode
    pub(crate) fn new(log_level: LogLevel, mode: StdOutLoggerMode) -> Self {
        Self::new_inner(Box::new(std::io::stdout()), log_level, mode)
    }

    // Create a new StdOutLogger with custom writer.
    // is used in tests.
    #[cfg(test)]
    pub(crate) fn new_with(
        writer: Box<dyn Write + Send + Sync>,
        log_level: LogLevel,
        mode: StdOutLoggerMode,
    ) -> Self {
        Self::new_inner(writer, log_level, mode)
    }

    fn new_inner(
        writer: Box<dyn Write + Send + Sync>,
        log_level: LogLevel,
        mode: StdOutLoggerMode,
    ) -> Self {
        match mode {
            StdOutLoggerMode::Immediate => Self {
                mode,
                sender: None,
                thread_handle: None,
                writer: Some(Arc::new(Mutex::new(writer))),
                log_level,
            },
            StdOutLoggerMode::Async {
                timeout_millis: timeout,
                buffer_limit,
            } => {
                let (sender, receiver) = mpsc::channel();
                let thread_handle = Some(spawn_writer_thread(
                    receiver,
                    writer,
                    Duration::from_millis(timeout),
                    buffer_limit,
                ));
                Self {
                    mode,
                    sender: Some(sender),
                    thread_handle,
                    writer: None,
                    log_level,
                }
            },
        }
    }
}

impl Drop for StdOutLogger {
    fn drop(&mut self) {
        match self.mode {
            StdOutLoggerMode::Immediate => {
                // Nothing to do for immediate mode
            },
            StdOutLoggerMode::Async { .. } => {
                // Send shutdown signal
                if let Some(sender) = &self.sender {
                    let _ = sender.send(LogMessage::Shutdown);
                }
                // Wait for thread to finish
                if let Some(handle) = self.thread_handle.take() {
                    let _ = handle.join();
                }
            },
        }
    }
}

// Implementation of LogWriter
impl LogWriter for StdOutLogger {
    fn log_any<T: Loggable>(&self, entry: T) {
        if !entry.can_log(self.log_level) {
            // do nothing
            return;
        }

        let serializer = move || match serde_json::to_value(&entry) {
            Ok(json) => json.to_string(),
            Err(err) => {
                let err_msg = format!("failed to serialize log entry to JSON: {err}");
                serde_json::to_value(ErrorLogEntry::from_loggable(&entry, err_msg.clone()))
                    .expect(&err_msg)
                    .to_string()
            },
        };
        match self.mode {
            StdOutLoggerMode::Immediate => {
                let json_string = serializer();
                if let Some(writer) = &self.writer {
                    let mut guard = writer
                        .lock()
                        .expect("failed to acquire lock on stdout writer");
                    let _ = guard.write_all(json_string.as_bytes());
                    let _ = guard.write_all(b"\n");
                }
            },
            StdOutLoggerMode::Async { .. } => {
                if let Some(sender) = &self.sender {
                    sender.send(LogMessage::Log(Box::new(serializer))).expect(
                        "could not send log entry to queue StdOutLogger, receiver was deallocated",
                    );
                }
            },
        }
    }

    fn log_fn<F, R>(&self, log_fn: crate::log::loggable_fn::LoggableFn<F>)
    where
        R: Loggable,
        F: Fn(crate::log::BaseLogEntry) -> R,
    {
        if !log_fn.can_log(self.log_level) {
            // do nothing
            return;
        }

        self.log_any(log_fn.build());
    }
}

// Test writer created for mocking LogWriter
#[cfg(test)]
#[derive(Clone)]
pub(crate) struct TestWriter {
    buf: Arc<Mutex<Vec<u8>>>,
}

#[cfg(test)]
impl TestWriter {
    pub(crate) fn new() -> Self {
        Self {
            buf: Arc::new(Mutex::new(Vec::new())),
        }
    }

    pub(crate) fn into_inner_buf(self) -> String {
        let buf = self.buf.lock().unwrap();
        String::from_utf8_lossy(buf.as_slice()).into_owned()
    }

    pub(crate) fn get_buf_contents(&self) -> String {
        let buf = self.buf.lock().unwrap();
        String::from_utf8_lossy(buf.as_slice()).into_owned()
    }
}

#[cfg(test)]
impl Write for TestWriter {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.buf.lock().unwrap().extend_from_slice(buf);
        Ok(buf.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use std::io::Write;

    use serde_json::json;

    use super::*;
    use crate::common::app_types::PdpID;
    use crate::log::log_strategy::LogEntryWithClientInfo;
    use crate::log::{BaseLogEntry, LogEntry, gen_uuid7};

    #[test]
    fn write_log_ok() {
        let pdp_id = PdpID::new();
        let app_name = None;
        // Create a log entry
        let log_entry = LogEntry {
            base: BaseLogEntry::new_decision(gen_uuid7()),
            auth_info: None,
            msg: "Test message".to_string(),
            error_msg: None,
            cedar_lang_version: None,
            cedar_sdk_version: None,
            build_commit: None,
            build_timestamp: None,
            batch_id: None,
        };
        let log_entry =
            LogEntryWithClientInfo::from_loggable(log_entry.clone(), pdp_id, app_name.clone());

        // Serialize the log entry to JSON
        let json_str = json!(log_entry).to_string();

        // Create a test writer
        let test_writer = TestWriter::new();
        let buffer = Box::new(test_writer.clone()) as Box<dyn Write + Send + Sync + 'static>;

        // Create logger with test writer
        let logger = StdOutLogger::new_with(buffer, LogLevel::TRACE, StdOutLoggerMode::Immediate);

        // Log the entry
        logger.log_any(log_entry);

        // Drop logger to ensure writer thread finishes
        drop(logger);

        // Check logged content
        let logged_content = test_writer.into_inner_buf();

        // Verify that the log entry was logged correctly
        assert_eq!(logged_content, json_str + "\n");
    }

    #[test]
    fn flush_by_timeout_even_with_continuous_messages() {
        use std::thread;

        let pdp_id = PdpID::new();
        let app_name = None;

        // Create a test writer
        let test_writer = TestWriter::new();
        let buffer = Box::new(test_writer.clone()) as Box<dyn Write + Send + Sync + 'static>;

        // Use a short timeout for testing (20ms)
        let flush_timeout_u64 = 20;
        let flush_timeout = Duration::from_millis(flush_timeout_u64);
        let logger = StdOutLogger::new_with(
            buffer,
            LogLevel::TRACE,
            StdOutLoggerMode::Async {
                timeout_millis: flush_timeout_u64,
                buffer_limit: StdOutLoggerMode::DEFAULT_BUFFER_LIMIT,
            },
        );

        // Create first log entry
        let log_entry1 = LogEntry {
            base: BaseLogEntry::new_decision(gen_uuid7()),
            auth_info: None,
            msg: "First message".to_string(),
            error_msg: None,
            cedar_lang_version: None,
            cedar_sdk_version: None,
            build_commit: None,
            build_timestamp: None,
            batch_id: None,
        };

        // Create second log entry
        let log_entry2 = LogEntry {
            base: BaseLogEntry::new_decision(gen_uuid7()),
            auth_info: None,
            msg: "Second message".to_string(),
            error_msg: None,
            cedar_lang_version: None,
            cedar_sdk_version: None,
            build_commit: None,
            build_timestamp: None,
            batch_id: None,
        };

        // Log first entry
        logger.log_any(log_entry1.clone());

        // Wait for half the timeout - buffer may still be empty or may have flushed early
        thread::sleep(flush_timeout / 2);
        let buf_contents = test_writer.get_buf_contents();
        if !buf_contents.is_empty() {
            // Flush may have happened early, ensure it contains the first message
            let expected_json = json!(log_entry1).to_string() + "\n";
            assert!(
                buf_contents.starts_with(&expected_json),
                "If buffer not empty, it should start with first message, got: {buf_contents}"
            );
        } // else buffer is empty, which is also valid

        logger.log_any(log_entry2);

        // Wait for the full timeout plus small margin (timer resets on each log, so wait full timeout after entry2)
        thread::sleep(flush_timeout + Duration::from_millis(5));

        // Buffer should now contain the first message (may also contain second message)
        let expected_json = json!(log_entry1).to_string() + "\n";
        let buf_contents = test_writer.get_buf_contents();
        assert!(
            buf_contents.starts_with(&expected_json),
            "First message should appear after flush timeout, got: {buf_contents}"
        );

        // Now continuously send messages at intervals shorter than timeout
        for i in 0..5 {
            let log_entry = LogEntry {
                base: BaseLogEntry::new_decision(gen_uuid7()),
                auth_info: None,
                msg: format!("Continuous message {i}"),
                error_msg: None,
                cedar_lang_version: None,
                cedar_sdk_version: None,
                build_commit: None,
                build_timestamp: None,
                batch_id: None,
            };
            let log_entry =
                LogEntryWithClientInfo::from_loggable(log_entry.clone(), pdp_id, app_name.clone());

            logger.log_any(log_entry);

            // Wait shorter than timeout
            thread::sleep(flush_timeout / 4);

            // Verify that previous continuous messages might not be flushed yet,
            // but they shouldn't block the flush of the first message (already verified)
        }

        // Wait for final flush
        thread::sleep(flush_timeout * 2);

        // Clean up logger
        drop(logger);

        // Verify that all messages eventually arrived
        let final_content = test_writer.into_inner_buf();
        assert!(
            final_content.contains("First message"),
            "First message should still be in final output"
        );
        for i in 0..5 {
            assert!(
                final_content.contains(&format!("Continuous message {i}")),
                "Continuous message {i} should be in final output"
            );
        }
    }
}