chronix-core 0.7.0

Core data model, types, errors, and configuration for the Chronix time-series database
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
//! Error types for the Chronix time-series database.
//!
//! Errors are organized hierarchically: each crate defines its own error type,
//! and [`ChronixError`] composes them all via `#[from]` conversions.

use std::path::PathBuf;

use thiserror::Error;

/// Top-level error type for the Chronix database.
///
/// All crate-level errors are composable into this type via `#[from]`.
#[derive(Debug, Error)]
pub enum ChronixError {
    /// WAL (Write-Ahead Log) errors.
    #[error("WAL error: {0}")]
    Wal(#[from] WalError),

    /// Schema validation and evolution errors.
    #[error("Schema error: {0}")]
    Schema(#[from] SchemaError),

    /// Configuration errors.
    #[error("Configuration error: {0}")]
    Config(#[from] ConfigError),

    /// Capacity exceeded (backpressure).
    #[error("Capacity exceeded: {0}")]
    Capacity(String),

    /// I/O errors.
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),
}

/// Write-Ahead Log errors.
#[derive(Debug, Error)]
pub enum WalError {
    /// Underlying I/O error.
    #[error("WAL I/O error: {0}")]
    Io(#[from] std::io::Error),

    /// Data corruption detected (CRC mismatch).
    #[error("WAL corruption at offset {offset} in {path}: {detail}")]
    Corruption {
        /// Byte offset in the WAL file where corruption was detected.
        offset: u64,
        /// Path to the corrupted WAL file.
        path: PathBuf,
        /// Human-readable detail about the corruption.
        detail: String,
    },

    /// Sequence number discontinuity detected during replay.
    #[error("WAL sequence skip: expected {expected}, got {got}")]
    SequenceSkip {
        /// The expected next sequence number.
        expected: u64,
        /// The actual sequence number encountered.
        got: u64,
    },

    /// WAL is full — too many unflushed WAL files.
    #[error("WAL full: {count} unflushed files exceed limit of {limit}")]
    Full {
        /// Current number of unflushed WAL files.
        count: usize,
        /// Maximum allowed unflushed WAL files.
        limit: usize,
    },

    /// The log belongs to a different on-disk format generation.
    ///
    /// Distinct from [`Corruption`](Self::Corruption) and from
    /// [`InvalidHeader`](Self::InvalidHeader): the header is well formed,
    /// the bytes are intact, and the reader is from another generation — so
    /// the remedy is to match the versions up rather than to restore. All
    /// four durable formats classify this the same way; see
    /// `chronix_engine::format`.
    #[error("{detail}")]
    UnsupportedVersion {
        /// Path to the WAL file.
        path: PathBuf,
        /// What was read, what this build expects, and what to do.
        detail: String,
    },

    /// Invalid WAL file header (wrong magic bytes).
    #[error("Invalid WAL header in {path}: {detail}")]
    InvalidHeader {
        /// Path to the WAL file with the invalid header.
        path: PathBuf,
        /// Description of what's wrong with the header.
        detail: String,
    },

    /// Payload exceeds the maximum allowed size per WAL record.
    #[error("WAL payload too large: {size} bytes exceeds limit of {limit}")]
    PayloadTooLarge {
        /// Actual payload size in bytes.
        size: usize,
        /// Maximum allowed payload size in bytes.
        limit: usize,
    },

    /// Internal lock was poisoned (indicates a prior panic while holding the lock).
    #[error("WAL lock poisoned: {0}")]
    LockPoisoned(String),

    /// The WAL writer's file is in an unknown state after a failed `fsync`
    /// or a failed rewind, and every write is refused until the database is
    /// reopened.
    ///
    /// The message names **reopening**, not `clear_poison()`. It named the
    /// latter for a long time, and no user of the `chronix` facade can call
    /// it: it is a `chronix-engine` method the facade does not re-export. An
    /// error that tells the operator to do something they cannot do is worse
    /// than one that says nothing.
    #[error(
        "WAL writer is poisoned after a failed fsync — the file's contents \
         are unknown; close and reopen the database to recover"
    )]
    Poisoned,
}

/// Schema validation and evolution errors.
#[derive(Debug, Error, Clone, PartialEq, Eq)]
pub enum SchemaError {
    /// Name is empty.
    #[error("{label} must not be empty")]
    EmptyName {
        /// Which entity had the empty name (e.g., "measurement name", "tag key").
        label: String,
    },

    /// Name exceeds maximum length.
    #[error("{label} too long: {length} bytes exceeds maximum of {max}")]
    NameTooLong {
        /// Which entity exceeded the limit.
        label: String,
        /// Actual byte length.
        length: usize,
        /// Maximum allowed length.
        max: usize,
    },

    /// Name contains null byte.
    #[error("{label} contains null byte (\\0)")]
    NullByte {
        /// Which entity contained the null byte.
        label: String,
    },

    /// Name/value contains a character that would break
    /// the canonical form encoding (e.g. `=` in tag values).
    #[error("{label} contains invalid character '{ch}' in \"{value}\"")]
    InvalidCharacter {
        /// Which entity contained the invalid character.
        label: String,
        /// The forbidden character.
        ch: char,
        /// The offending value for diagnostic context.
        value: String,
    },

    /// Too many tags on a series key.
    #[error("Too many tags: {count} exceeds maximum of {max}")]
    TooManyTags {
        /// Actual tag count.
        count: usize,
        /// Maximum allowed.
        max: usize,
    },

    /// Point has no fields.
    #[error("Point must have at least one field")]
    EmptyFields,

    /// Too many fields on a single point.
    #[error("Too many fields: {count} exceeds maximum of {max}")]
    TooManyFields {
        /// Actual field count.
        count: usize,
        /// Maximum allowed.
        max: usize,
    },

    /// A field value failed validation (e.g., non-finite f64, oversized string).
    #[error("Invalid value for field '{field}': {reason}")]
    InvalidFieldValue {
        /// Field name with the invalid value.
        field: String,
        /// Why the value is invalid.
        reason: String,
    },

    /// Type conflict: a field already exists with a different type.
    #[error(
        "Type conflict for field '{field}' in measurement '{measurement}': expected {expected}, got {got}"
    )]
    TypeConflict {
        /// Measurement name where the conflict occurred.
        measurement: String,
        /// Field name with the type conflict.
        field: String,
        /// The existing (expected) type.
        expected: String,
        /// The conflicting (received) type.
        got: String,
    },

    /// A decimal value carries more fractional digits than its column
    /// declares, so storing it would have to round.
    ///
    /// Separate from [`TypeConflict`](Self::TypeConflict) because the fix is
    /// different: the types agree, the *scale* does not, and the writer
    /// either rounds the value itself or declares the column with the scale
    /// it needs before the first write.
    #[error(
        "Decimal scale conflict for field '{field}' in measurement '{measurement}': \
         the column stores {declared} fractional digit(s) and the value {value} needs {got}. \
         Declare the field with the scale it needs before the first write, or round the value."
    )]
    DecimalScaleConflict {
        /// Measurement name where the conflict occurred.
        measurement: String,
        /// Field name with the scale conflict.
        field: String,
        /// The column's declared scale.
        declared: u8,
        /// The value's scale.
        got: u8,
        /// The offending value, rendered exactly.
        value: String,
    },

    /// Measurement not found.
    #[error("Measurement '{0}' not found")]
    MeasurementNotFound(String),

    /// Internal lock was poisoned (indicates a prior panic while holding the lock).
    #[error("Schema lock poisoned: {0}")]
    LockPoisoned(String),

    /// An entity name failed validation.
    #[error("Invalid name '{name}': {reason}")]
    InvalidName {
        /// The invalid name.
        name: String,
        /// Why the name is invalid.
        reason: String,
    },
}

/// Configuration errors.
#[derive(Debug, Error)]
pub enum ConfigError {
    /// A required field was not set.
    #[error("missing required field: {field}")]
    MissingField {
        /// Name of the missing field.
        field: &'static str,
    },

    /// A configuration value failed validation.
    #[error("invalid configuration: {message}")]
    Validation {
        /// Human-readable validation failure description.
        message: String,
    },

    /// Failed to read the configuration file.
    #[error("failed to read config file: {0}")]
    Io(#[from] std::io::Error),

    /// Failed to parse TOML content.
    #[error("failed to parse TOML: {0}")]
    Parse(#[from] toml::de::Error),
}

/// A specialized `Result` type for Chronix operations.
pub type Result<T> = std::result::Result<T, ChronixError>;

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

    #[test]
    fn chronix_error_from_wal() {
        let wal_err = WalError::Full { count: 5, limit: 4 };
        let err: ChronixError = wal_err.into();
        let msg = format!("{err}");
        assert!(msg.contains("WAL"));
        assert!(msg.contains('5'));
    }

    #[test]
    fn chronix_error_from_schema() {
        let schema_err = SchemaError::EmptyFields;
        let err: ChronixError = schema_err.into();
        assert!(format!("{err}").contains("field"));
    }

    #[test]
    fn chronix_error_from_io() {
        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "gone");
        let err: ChronixError = io_err.into();
        assert!(format!("{err}").contains("gone"));
    }

    #[test]
    fn schema_error_type_conflict_message() {
        let err = SchemaError::TypeConflict {
            measurement: "cpu".to_string(),
            field: "value".to_string(),
            expected: "f64".to_string(),
            got: "i64".to_string(),
        };
        let msg = format!("{err}");
        assert!(msg.contains("value"));
        assert!(msg.contains("f64"));
        assert!(msg.contains("i64"));
    }

    #[test]
    fn wal_error_corruption_message() {
        let err = WalError::Corruption {
            offset: 1024,
            path: PathBuf::from("/data/wal_1.cxwl"),
            detail: "CRC mismatch".to_string(),
        };
        let msg = err.to_string();
        assert!(msg.contains("1024"));
        assert!(msg.contains("CRC"));
    }

    #[test]
    fn wal_error_sequence_skip_message() {
        let err = WalError::SequenceSkip {
            expected: 5,
            got: 8,
        };
        let msg = err.to_string();
        assert!(msg.contains('5'));
        assert!(msg.contains('8'));
    }

    #[test]
    fn wal_error_invalid_header_message() {
        let err = WalError::InvalidHeader {
            path: PathBuf::from("/data/wal.cxwl"),
            detail: "bad magic".into(),
        };
        let msg = err.to_string();
        assert!(msg.contains("bad magic"));
    }

    #[test]
    fn wal_error_lock_poisoned_message() {
        let err = WalError::LockPoisoned("inner mutex".into());
        assert!(err.to_string().contains("inner mutex"));
    }

    #[test]
    fn wal_error_io_message() {
        let err = WalError::Io(std::io::Error::new(
            std::io::ErrorKind::PermissionDenied,
            "read-only",
        ));
        assert!(err.to_string().contains("read-only"));
    }

    #[test]
    fn wal_error_full_message() {
        let err = WalError::Full {
            count: 10,
            limit: 4,
        };
        let msg = err.to_string();
        assert!(msg.contains("10"));
        assert!(msg.contains('4'));
    }

    #[test]
    fn wal_error_payload_too_large_message() {
        let err = WalError::PayloadTooLarge {
            size: 512_000_000,
            limit: 268_435_456,
        };
        let msg = err.to_string();
        assert!(msg.contains("512000000"));
        assert!(msg.contains("268435456"));
    }

    #[test]
    fn schema_error_lock_poisoned_message() {
        let err = SchemaError::LockPoisoned("registry lock".into());
        assert!(err.to_string().contains("registry lock"));
    }

    #[test]
    fn schema_error_measurement_not_found_message() {
        let err = SchemaError::MeasurementNotFound("disk".into());
        assert!(err.to_string().contains("disk"));
    }

    #[test]
    fn config_error_missing_field_message() {
        let err = ConfigError::MissingField { field: "data_dir" };
        assert!(err.to_string().contains("data_dir"));
    }

    #[test]
    fn config_error_validation_message() {
        let err = ConfigError::Validation {
            message: "too small".into(),
        };
        assert!(err.to_string().contains("too small"));
    }

    #[test]
    fn chronix_error_from_config() {
        let config_err = ConfigError::MissingField { field: "data_dir" };
        let err: ChronixError = config_err.into();
        assert!(err.to_string().contains("data_dir"));
    }
}