pinenut-log 0.0.2

An extremely high performance logging system for clients (iOS, Android, Desktop), written in Rust.
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
//! The `Logger` implementation.

use std::{
    io,
    ops::{Deref, DerefMut},
    sync::{Arc, Mutex},
};

use thiserror::Error;

use crate::{
    buffer::{self, Buffer, EitherMemory, Memory},
    chunk::Chunk,
    codec::{AccumulationEncoder, EncodingError},
    common,
    compress::{CompressOp, CompressionError, Compressor, ZstdCompressor},
    encrypt::{
        ecdh::{self, PublicKey, EMPTY_PUBLIC_KEY},
        AesEncryptor, EncryptOp, EncryptionError, Encryptor,
    },
    logfile::{self, Logfile},
    mmap::Mmap,
    runloop::{self, Handle as RunloopHandle, Runloop},
    ChunkError, Config, Domain, Record, RunloopError, TimeDimension, Tracker,
    MMAP_BUFFER_EXTENSION,
};

/// The error type for [`Logger`].
///
/// Errors occurred in the logger can be track by the specified [`Tracker`].
#[derive(Error, Debug)]
pub enum Error {
    #[error("encoding: {0}")]
    Encode(#[from] EncodingError),
    #[error("compression: {0}")]
    Compress(#[from] CompressionError),
    #[error("encryption: {0}")]
    Encrypt(#[from] EncryptionError),
    #[error("chunk: {0}")]
    Chunk(#[from] ChunkError),
    #[error("IO runloop: {0}")]
    IoRunloop(#[from] RunloopError),
    #[error("IO: {0}")]
    Io(#[from] io::Error),
}

/// The `Pinenut` logger.
pub struct Logger {
    inner: Mutex<LoggerInner>,
}

impl Logger {
    /// Constructs a new `Logger`.
    #[inline]
    pub fn new(domain: Domain, config: Config) -> Self {
        Self { inner: Mutex::new(LoggerInner::new_inner(domain, config)) }
    }

    /// Logs the record.
    ///
    /// The low-level IO operations are performed asynchronously.
    #[inline]
    pub fn log(&self, record: &Record) {
        self.inner.lock().unwrap().on(Operation::Input(record));
    }

    /// Flushes any buffered records asynchronously.
    ///
    /// The low-level IO operations are performed asynchronously.
    #[inline]
    pub fn flush(&self) {
        self.inner.lock().unwrap().on(Operation::Rotate);
    }

    /// Deletes the expired log files with lifetime (seconds).
    ///
    /// The low-level IO operations are performed asynchronously.
    #[inline]
    pub fn trim(&self, lifetime: u64) {
        self.inner.lock().unwrap().trim(lifetime);
    }

    /// Flushes then Shuts down the logger.
    ///
    /// All asynchronous IO operations will be waiting to complete.
    #[inline]
    pub fn shutdown(self) {
        let mut inner = self.inner.into_inner().unwrap();
        inner.on(Operation::Rotate);
        inner.shutdown();
    }
}

// ============ Internal ============

/// Represents the logger context.
struct Context {
    domain: Arc<Domain>,
    pub_key: PublicKey,
    rotation: TimeDimension,
    tracker: Option<Tracker>,
}

impl Context {
    #[inline]
    fn new(
        domain: Domain,
        pub_key: Option<PublicKey>,
        rotation: TimeDimension,
        tracker: Option<Tracker>,
    ) -> Self {
        Self {
            domain: Arc::new(domain),
            pub_key: pub_key.unwrap_or(EMPTY_PUBLIC_KEY),
            rotation,
            tracker,
        }
    }

    /// Determines whether the chunk needs to be rotated.
    #[inline]
    pub(crate) fn rotate_chunk<B>(&self, chunk: &Chunk<B>, new_record: &Record) -> bool
    where
        B: Deref<Target = [u8]>,
    {
        !self.chunk_dimension().check_match(chunk.start_datetime(), new_record.meta().datetime())
    }

    /// Determines whether the log file needs to be rotated.
    #[inline]
    pub(crate) fn rotate_file<B>(&self, logfile: &Logfile, new_chunk: &Chunk<B>) -> bool
    where
        B: Deref<Target = [u8]>,
    {
        !self.file_dimension().check_match(new_chunk.start_datetime(), logfile.datetime())
    }

    /// Time dimension for chunk rotation.
    #[inline]
    fn chunk_dimension(&self) -> TimeDimension {
        self.rotation
    }

    /// Time dimension for log file rotation.
    #[inline]
    fn file_dimension(&self) -> TimeDimension {
        match self.chunk_dimension() {
            TimeDimension::Minute => TimeDimension::Hour,
            TimeDimension::Hour => TimeDimension::Day,
            TimeDimension::Day => TimeDimension::Day,
        }
    }
}

/// Returns a closure that reports the error to tracker.
macro_rules! track {
    ($tracker:expr) => {{
        |err| {
            if let Some(ref tracker) = $tracker {
                tracker.track(err.into(), file!(), line!());
            }
        }
    }};
}

/// The `Core Logger` associated with the specified `Compressor`, `Encryptor` and
/// `Memory`.
///
/// The current version of `Pinenut` will use the `zstd` compression algorithm and
/// `AES` encryption algorithm to process the logs.
type LoggerInner = Core<Option<ZstdCompressor>, Option<AesEncryptor>, EitherMemory>;

impl LoggerInner {
    #[inline]
    pub fn new_inner(domain: Domain, config: Config) -> Self {
        let memory = Self::initialize_memory(&domain, &config);

        let keys =
            config.key.and_then(|k| ecdh::Keys::new(&k).map_err(track!(config.tracker)).ok());
        let encryptor = keys.as_ref().map(|k| AesEncryptor::new(&k.encryption_key));

        let compressor =
            ZstdCompressor::new(config.compression_level).map_err(track!(config.tracker)).ok();

        let context =
            Context::new(domain, keys.map(|k| k.public_key), config.rotation, config.tracker);

        Self::new(context, compressor, encryptor, memory)
    }

    fn initialize_memory(domain: &Domain, config: &Config) -> EitherMemory {
        config
            .use_mmap
            .then(|| {
                let path =
                    domain.directory.join(&domain.identifier).with_extension(MMAP_BUFFER_EXTENSION);
                Mmap::new(path, config.buffer_len).map(EitherMemory::Mmap)
            })
            .and_then(|mmap| mmap.map_err(track!(config.tracker)).ok())
            .unwrap_or_else(|| {
                let mut vec = Vec::with_capacity(config.buffer_len);
                #[allow(clippy::uninit_vec)]
                unsafe {
                    vec.set_len(config.buffer_len);
                }
                EitherMemory::Vec(vec)
            })
    }
}

/// Operation for `Core` and `Processor`.
#[derive(Clone, Copy)]
enum Operation<'a> {
    Input(&'a Record<'a>),
    Rotate,
    Writeback,
}

/// Represents the `Core Logger`.
struct Core<C, E, M> {
    context: Arc<Context>,
    processor: Processor<C, E>,
    buffer: Buffer<M>,
    io_runloop: Runloop<IoEvent>,
}

impl<C, E, M> Core<C, E, M>
where
    C: Compressor,
    E: Encryptor,
    M: Memory,
{
    fn new(context: Context, compressor: C, encryptor: E, memory: M) -> Self {
        let context = Arc::new(context);
        let processor = Processor::new(compressor, encryptor);

        let (input_buffer, output_buffer) = Self::initialize_buffer(memory, &context);
        let io_runloop = Io::new(Arc::clone(&context), output_buffer).run();

        let mut core = Self { context, processor, buffer: input_buffer, io_runloop };
        // Attempts to write previously unwritten chunk to the logfile.
        core.on(Operation::Writeback);

        core
    }

    fn initialize_buffer(memory: M, context: &Context) -> (Buffer<M>, Buffer<M>) {
        let (mut input, mut output) = buffer::initialize(memory);
        {
            let (mut input_chunk, mut output_chunk) =
                (Chunk::bind(input.handle()), Chunk::bind(output.handle()));

            // If either side of the buffer is invalid, both sides need to be initialized.
            // Due to the internal structure of the double buffer system, when the buffer length
            // configuration is changed, one chunk must be invalid.
            if !input_chunk.validate() || !output_chunk.validate() {
                let now = chrono::Utc::now();
                input_chunk.initialize(now, context.pub_key);
                output_chunk.initialize(now, context.pub_key);
            }
        }
        (input, output)
    }

    fn on(&mut self, operation: Operation) {
        let mut chunk = Chunk::bind(self.buffer.handle());

        let write_operation = match operation {
            Operation::Rotate => Some(operation),
            // Writes back if chunk payload is not empty.
            Operation::Writeback => (chunk.payload_len() > 0).then(|| {
                chunk.set_writeback();
                operation
            }),
            // Checks if rotation is required.
            Operation::Input(record) => (chunk.is_almost_full()
                || self.context.rotate_chunk(&chunk, record))
            .then_some(Operation::Rotate),
        };

        if let Some(write_operation) = write_operation {
            self.processor
                .process(write_operation, &mut chunk)
                .unwrap_or_else(track!(self.context.tracker));

            // If the length of the chunk is greater than 0, it means that there are bytes to be
            // written to the file, we need to switch the buffer and perform IO write operation,
            // otherwise we can reuse the chunk and not perform IO write operation.
            if chunk.payload_len() > 0 {
                // Switches the double buffering system then rebinds the chunk.
                drop(chunk);
                self.buffer.switch();
                chunk = Chunk::bind(self.buffer.handle());

                // Performs asynchronous file write IO operation.
                self.io_runloop
                    .on(IoEvent::WriteChunk)
                    .unwrap_or_else(track!(self.context.tracker));
            }

            // Re-initialize the chunk.
            let datetime = match operation {
                Operation::Input(record) => record.meta().datetime(),
                Operation::Rotate | Operation::Writeback => chrono::Utc::now(),
            };
            chunk.initialize(datetime, self.context.pub_key);
        }

        if let Operation::Input(record) = operation {
            self.processor
                .process(Operation::Input(record), &mut chunk)
                .unwrap_or_else(track!(self.context.tracker));
        }
    }

    #[inline]
    fn trim(&mut self, lifetime: u64) {
        self.io_runloop.on(IoEvent::Trim { lifetime }).unwrap_or_else(track!(self.context.tracker));
    }

    #[inline]
    fn shutdown(self) {
        self.io_runloop.on(IoEvent::Shutdown).unwrap_or_else(track!(self.context.tracker));
        _ = self.io_runloop.join();
    }
}

/// The Log processor. It processes the log record step by step.
///
/// # Workflow
///
/// ```plain
/// ┌──────────┐   ┌──────────┐   ┌───────────┐   ┌───────────────────────────┐
/// │  Encode  │──▶│ Compress │──▶│  Encrypt  │──▶│  Write to Chunk (Buffer)  │
/// └──────────┘   └──────────┘   └───────────┘   └───────────────────────────┘
/// ```
struct Processor<C, E> {
    encoder: AccumulationEncoder,
    compressor: C,
    encryptor: E,
}

impl<C, E> Processor<C, E>
where
    C: Compressor,
    E: Encryptor,
{
    /// Length of `encoder buffer`.
    ///
    /// A buffer of 256 bytes should be sufficient for encoding of a log.
    const ENCODER_BUFFER_LEN: usize = 256;

    #[inline]
    fn new(compressor: C, encryptor: E) -> Self {
        let encoder = AccumulationEncoder::new(Self::ENCODER_BUFFER_LEN);
        Self { encoder, compressor, encryptor }
    }

    fn process<B>(&mut self, operation: Operation, chunk: &mut Chunk<B>) -> Result<(), Error>
    where
        B: DerefMut<Target = [u8]>,
    {
        type FnSink<F> = common::FnSink<F, Error>;

        let mut to_chunk = FnSink::new(|bytes: &[u8]| chunk.write(bytes).map_err(Into::into));

        let mut to_encryptor = FnSink::new(|bytes: &[u8]| {
            self.encryptor.encrypt(EncryptOp::Input(bytes), &mut to_chunk)
        });

        let mut to_compressor = FnSink::new(|bytes: &[u8]| {
            self.compressor.compress(CompressOp::Input(bytes), &mut to_encryptor)
        });

        match operation {
            Operation::Input(record) => {
                self.encoder.encode(record, &mut to_compressor)?;
                self.compressor.compress(CompressOp::Flush, &mut to_encryptor)?;
                chunk.set_end_datetime(record.meta().datetime());
            }

            Operation::Rotate => {
                self.compressor.compress(CompressOp::End, &mut to_encryptor)?;
                self.encryptor.encrypt(EncryptOp::Flush, &mut to_chunk)?;
            }

            Operation::Writeback => { /* Do nothing on writeback. */ }
        }

        Ok(())
    }
}

/// The IO handler. It is responsible for all file IO interactions.
///
/// It implements the [`runloop::Handle`] trait so that it can invoke a runloop to
/// handle IO events asynchronously.
struct Io<M> {
    context: Arc<Context>,
    buffer: Buffer<M>,
    logfile: Option<Logfile>,
}

/// IO events that the [`Io`] handler can receive.
enum IoEvent {
    /// Writes chunk to log file.
    WriteChunk,
    /// Deletes the expired log files.
    Trim { lifetime: u64 },
    /// Shuts down the IO handler.
    Shutdown,
}

impl<M> Io<M>
where
    M: Memory,
{
    #[inline]
    fn new(context: Arc<Context>, buffer: Buffer<M>) -> Self {
        let mut io = Io { context, buffer, logfile: None };
        // Attempts to write previously unwritten chunk to the logfile.
        if Chunk::bind(io.buffer.handle()).payload_len() > 0 {
            io.write_chunk();
        }
        io
    }

    /// Writes chunk to log file.
    fn write_chunk(&mut self) {
        let mut chunk = Chunk::bind(self.buffer.handle());
        // The chunk is empty, there is no need to write to the logfile.
        if chunk.payload_len() == 0 {
            return;
        }

        self.logfile.take_if(|f| self.context.rotate_file(f, &chunk));

        let logfile = if let Some(logfile) = &mut self.logfile {
            logfile
        } else {
            self.logfile = Some(Logfile::new(
                Arc::clone(&self.context.domain),
                chunk.start_datetime(),
                logfile::Mode::Write,
            ));
            // SAFETY: a `None` variant for `logfile` would have been replaced by a `Some`
            // variant in the code above.
            unsafe { self.logfile.as_mut().unwrap_unchecked() }
        };

        logfile.write(&chunk).unwrap_or_else(track!(self.context.tracker));
        logfile.flush().unwrap_or_else(track!(self.context.tracker));

        // Sets the chunk length to 0 to indicate that the chunk has finished writing to the
        // logfile and will not be written again.
        chunk.clear();
    }

    /// Deletes the expired log files.
    #[inline]
    fn trim(&mut self, lifetime: u64) {
        let expires = chrono::Utc::now().timestamp().saturating_sub_unsigned(lifetime);

        if let Ok(logfiles) = Logfile::logfiles(&self.context.domain, logfile::Mode::Read)
            .map_err(track!(self.context.tracker))
        {
            logfiles
                .filter(|f| f.datetime().timestamp() < expires)
                .for_each(|file| file.delete().unwrap_or_else(track!(self.context.tracker)));
        }
    }
}

impl<M> RunloopHandle for Io<M>
where
    M: Memory,
{
    type Event = IoEvent;

    #[inline]
    fn handle(&mut self, event: Self::Event, context: &mut runloop::Context) {
        match event {
            IoEvent::WriteChunk => self.write_chunk(),
            IoEvent::Trim { lifetime } => self.trim(lifetime),
            IoEvent::Shutdown => context.stop(),
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        chunk, chunk::Chunk, codec::Decode, compress::ZstdCompressor, encrypt::AesEncryptor,
        logger, logger::Operation, Record, RecordBuilder,
    };

    #[test]
    fn test_processor() {
        type Processor = logger::Processor<Option<ZstdCompressor>, Option<AesEncryptor>>;
        let mut processor = Processor::new(None, None);

        let mut memory = Vec::<u8>::with_capacity(256);
        unsafe {
            memory.set_len(256);
        }

        fn test_process<'a>(
            processor: &mut Processor,
            memory: &mut Vec<u8>,
            contents: impl IntoIterator<Item = &'a str>,
        ) {
            let mut chunk = Chunk::bind(memory.as_mut_slice());
            chunk.initialize(chrono::Utc::now(), [0; 33]);

            let records = contents
                .into_iter()
                .map(|c| RecordBuilder::new().content(c).build())
                .collect::<Vec<_>>();

            for record in &records {
                processor.process(Operation::Input(&record), &mut chunk).unwrap();
            }
            processor.process(Operation::Rotate, &mut chunk).unwrap();

            let payload_len = chunk.payload_len();
            let mut payload = &memory[chunk::Header::LEN..chunk::Header::LEN + payload_len];

            for record in records {
                let new_record = Record::decode(&mut payload).unwrap();
                assert_eq!(record, new_record);
            }

            assert_eq!(payload.len(), 0);
        }

        test_process(&mut processor, &mut memory, []);
        test_process(&mut processor, &mut memory, ["Hello", "World"]);
    }
}