msr-core 0.3.7

Industrial Automation Toolbox - Common core components
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
//! Journaling features

use std::{fmt, num::NonZeroUsize, time::SystemTime};

use serde::{Deserialize, Serialize};
use thiserror::Error;
use ulid::Ulid;

use crate::{
    storage::{
        self, decode_binary_data_from_string, encode_binary_data_into_string, BinaryDataFormat,
        CreatedAtOffset, CreatedAtOffsetNanos, ReadableRecordPrelude, RecordPreludeFilter,
        RecordStorageBase, RecordStorageWrite, WritableRecordPrelude,
    },
    time::{SystemInstant, Timestamp},
};

#[cfg(feature = "csv-event-journal")]
pub mod csv;

#[derive(Debug, Error)]
pub enum Error {
    #[error(transparent)]
    Storage(#[from] storage::Error),
    #[error(transparent)]
    Other(#[from] anyhow::Error),
}

impl From<std::io::Error> for Error {
    fn from(from: std::io::Error) -> Self {
        Self::Storage(storage::Error::Io(from))
    }
}

pub type Result<T> = std::result::Result<T, Error>;

pub type SeverityValue = u8;

#[derive(Debug)]
pub struct SeverityValues;

impl SeverityValues {
    pub const DIAGNOSTIC_VERBOSE: SeverityValue = 1;
    pub const DIAGNOSTIC: SeverityValue = 2;
    pub const INFORMATION_VERBOSE: SeverityValue = 3;
    pub const INFORMATION: SeverityValue = 4;
    pub const WARNING: SeverityValue = 5;
    pub const WARNING_UNEXPECTED: SeverityValue = 6;
    pub const ERROR: SeverityValue = 7;
    pub const ERROR_CRITICAL: SeverityValue = 8;
}

/// A measure for the significance and/or priority of an entry.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
pub enum Severity {
    DiagnosticVerbose = SeverityValues::DIAGNOSTIC_VERBOSE as isize,

    Diagnostic = SeverityValues::DIAGNOSTIC as isize,

    InformationVerbose = SeverityValues::INFORMATION_VERBOSE as isize,

    Information = SeverityValues::INFORMATION as isize,

    Warning = SeverityValues::WARNING as isize,

    WarningUnexpected = SeverityValues::WARNING_UNEXPECTED as isize,

    Error = SeverityValues::ERROR as isize,

    ErrorCritical = SeverityValues::ERROR_CRITICAL as isize,
}

impl Severity {
    #[must_use]
    pub fn is_diagnostic(self) -> bool {
        self == Self::Diagnostic || self == Self::InformationVerbose
    }

    #[must_use]
    pub fn is_information(self) -> bool {
        self == Self::Information || self == Self::InformationVerbose
    }

    #[must_use]
    pub fn is_warning(self) -> bool {
        self == Self::Warning || self == Self::WarningUnexpected
    }

    #[must_use]
    pub fn is_error(self) -> bool {
        self == Self::Error || self == Self::ErrorCritical
    }

    #[must_use]
    pub const fn value(self) -> SeverityValue {
        self as SeverityValue
    }
}

impl From<Severity> for SeverityValue {
    fn from(from: Severity) -> Self {
        from.value()
    }
}

#[derive(Error, Debug)]
pub enum TryFromSeverityValueError {
    #[error("invalid value {0}")]
    InvalidValue(SeverityValue),
}

impl TryFrom<SeverityValue> for Severity {
    type Error = TryFromSeverityValueError;

    fn try_from(from: SeverityValue) -> std::result::Result<Self, TryFromSeverityValueError> {
        match from {
            SeverityValues::DIAGNOSTIC_VERBOSE => Ok(Severity::DiagnosticVerbose),
            SeverityValues::DIAGNOSTIC => Ok(Severity::Diagnostic),
            SeverityValues::INFORMATION_VERBOSE => Ok(Severity::InformationVerbose),
            SeverityValues::INFORMATION => Ok(Severity::Information),
            SeverityValues::WARNING => Ok(Severity::Warning),
            SeverityValues::WARNING_UNEXPECTED => Ok(Severity::WarningUnexpected),
            SeverityValues::ERROR => Ok(Severity::Error),
            SeverityValues::ERROR_CRITICAL => Ok(Severity::ErrorCritical),
            _ => Err(TryFromSeverityValueError::InvalidValue(from)),
        }
    }
}

pub type ScopeValue = String;

/// Symbolic scope name
///
/// A technical identifier for the origin or source of the
/// event. It uniquely identifies the system component and
/// the context within this component that caused the event.
///
/// The number of possible values should be restricted to
/// limited, predefined set. Those values usually depend on
/// the system configuration and may follow some naming
/// conventions that could be parsed.
// Symbolic name that identifies the scope of a journal entry.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Scope(pub String);

impl From<ScopeValue> for Scope {
    fn from(inner: ScopeValue) -> Self {
        Self(inner)
    }
}

impl From<Scope> for ScopeValue {
    fn from(from: Scope) -> Self {
        let Scope(inner) = from;
        inner
    }
}

impl AsRef<ScopeValue> for Scope {
    fn as_ref(&self) -> &ScopeValue {
        let Self(inner) = self;
        inner
    }
}

impl fmt::Display for Scope {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

pub type CodeValue = i32;

#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
pub struct Code(pub CodeValue);

impl From<CodeValue> for Code {
    fn from(inner: CodeValue) -> Self {
        Self(inner)
    }
}

impl From<Code> for CodeValue {
    fn from(from: Code) -> Self {
        let Code(inner) = from;
        inner
    }
}

/// A journal entry
///
/// Stores information about events or incidents that happened in the system.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Entry {
    pub occurred_at: Timestamp,

    pub severity: Severity,

    /// Identifies context: component -> sub-component -> use case -> function -> ...
    pub scope: Scope,

    /// Scope-dependent code
    pub code: Code,

    /// Textual context description (human-readable)
    pub text: Option<String>,

    /// Binary context data (machine-readable)
    ///
    /// Example: Custom JSON data serialized as UTF-8
    pub data: Option<Vec<u8>>,
}

pub type RecordIdType = String;

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct RecordId(pub RecordIdType);

impl From<RecordIdType> for RecordId {
    fn from(inner: RecordIdType) -> Self {
        Self(inner)
    }
}

impl From<RecordId> for RecordIdType {
    fn from(from: RecordId) -> Self {
        let RecordId(inner) = from;
        inner
    }
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct RecordPrelude {
    pub id: RecordId,

    pub created_at_offset: CreatedAtOffset,
}

impl WritableRecordPrelude for RecordPrelude {
    fn set_created_at_offset(&mut self, created_at_offset: CreatedAtOffset) {
        debug_assert_eq!(self.created_at_offset, Default::default()); // not yet initialized
        self.created_at_offset = created_at_offset;
    }
}

/// A recorded journal entry
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Record {
    pub prelude: RecordPrelude,

    pub entry: Entry,
}

impl ReadableRecordPrelude for Record {
    fn created_at_offset(&self) -> CreatedAtOffset {
        self.prelude.created_at_offset
    }
}

impl WritableRecordPrelude for Record {
    fn set_created_at_offset(&mut self, created_at_offset: CreatedAtOffset) {
        self.prelude.set_created_at_offset(created_at_offset);
    }
}

#[derive(Debug, Default, Clone, Eq, PartialEq)]
pub struct RecordFilter {
    pub prelude: RecordPreludeFilter,
    pub min_severity: Option<Severity>,
    pub any_scopes: Option<Vec<Scope>>,
    pub any_codes: Option<Vec<Code>>,
}

pub trait RecordPreludeGenerator {
    fn generate_prelude(&self) -> Result<(SystemInstant, RecordPrelude)>;
}

#[derive(Debug)]
pub struct DefaultRecordPreludeGenerator;

impl RecordPreludeGenerator for DefaultRecordPreludeGenerator {
    fn generate_prelude(&self) -> Result<(SystemInstant, RecordPrelude)> {
        let id = RecordId::from(Ulid::new().to_string());
        Ok((
            SystemInstant::now(),
            RecordPrelude {
                id,
                created_at_offset: Default::default(),
            },
        ))
    }
}

pub trait RecordStorage: RecordStorageBase + RecordStorageWrite<Record> {
    fn recent_records(&mut self, limit: NonZeroUsize) -> Result<Vec<StoredRecord>>;

    fn filter_records(
        &mut self,
        limit: NonZeroUsize,
        filter: RecordFilter,
    ) -> Result<Vec<StoredRecord>>;
}

// Fields ordered according to filtering and access patterns, i.e. most
// frequently used fields first.
#[derive(Debug, Serialize, Deserialize)]
struct StorageRecord {
    created_at_offset_ns: CreatedAtOffsetNanos,

    occurred_at: Timestamp,

    severity: SeverityValue,

    scope: String,

    code: CodeValue,

    id: String,

    text: Option<String>,

    data: Option<String>,
}

impl StorageRecord {
    fn try_new(record: Record, binary_data_format: BinaryDataFormat) -> anyhow::Result<Self> {
        let Record {
            prelude:
                RecordPrelude {
                    id,
                    created_at_offset,
                },
            entry:
                Entry {
                    occurred_at,
                    severity,
                    scope,
                    code,
                    text,
                    data,
                },
        } = record;
        let data = data
            .map(|data| encode_binary_data_into_string(data, binary_data_format))
            .transpose()?;
        Ok(Self {
            created_at_offset_ns: created_at_offset.into(),
            occurred_at,
            severity: SeverityValue::from(severity),
            scope: scope.0,
            code: code.0,
            id: id.0,
            text,
            data,
        })
    }
}

impl ReadableRecordPrelude for StorageRecord {
    fn created_at_offset(&self) -> CreatedAtOffset {
        self.created_at_offset_ns.into()
    }
}

impl WritableRecordPrelude for StorageRecord {
    fn set_created_at_offset(&mut self, created_at_offset: CreatedAtOffset) {
        self.created_at_offset_ns = created_at_offset.into();
    }
}

/// A stored journal entry
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct StoredRecordPrelude {
    pub id: RecordId,

    pub created_at: SystemTime,
}

/// A stored journal entry
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct StoredRecord {
    pub prelude: StoredRecordPrelude,

    pub entry: Entry,
}

impl StoredRecord {
    // Only used when a storage backend like CSV is enabled
    #[allow(dead_code)]
    fn try_restore(
        created_at_origin: SystemTime,
        record: StorageRecord,
        binary_data_format: BinaryDataFormat,
    ) -> Result<Self> {
        let StorageRecord {
            created_at_offset_ns,
            occurred_at,
            severity,
            scope,
            code,
            id,
            text,
            data,
        } = record;
        let created_at_offset = CreatedAtOffset::from(created_at_offset_ns);
        let created_at = created_at_offset.system_time_from_origin(created_at_origin);
        let prelude = StoredRecordPrelude {
            id: id.into(),
            created_at,
        };
        let data = data
            .map(|data| decode_binary_data_from_string(data, binary_data_format))
            .transpose()?;
        Ok(Self {
            prelude,
            entry: Entry {
                occurred_at,
                severity: severity.try_into().map_err(anyhow::Error::from)?,
                scope: scope.into(),
                code: code.into(),
                text,
                data,
            },
        })
    }
}