Skip to main content

hayson_binding_shared/
errors.rs

1use std::io;
2use std::path::Path;
3
4use hayson_engine::atomic::AtomicTemporaryFileError;
5use hayson_engine::catalog::MigrateFormat1Error;
6use hayson_engine::database::DatabaseError;
7use hayson_engine::errors::{
8    HaysonCipherError, HaysonCorruptLogError, HaysonImageClashError, HaysonImageTooLargeError,
9    HaysonIndexMismatchError, HaysonLogReplacedError,
10};
11use hayson_engine::lock::{DirLockError, LockedError};
12use hayson_engine::table::TableError;
13use hayson_engine::txn::TxnError;
14use serde_json::{json, Map, Value};
15
16/// Envelope version of the JSON carried in every thrown `Error.message`. Bumped only if the shape
17/// below changes incompatibly — the TS shim reads it before trusting `code`.
18pub const ENVELOPE_VERSION: u64 = 1;
19
20/// Stable, machine-readable tags a TS shim switches on to re-throw the matching `HaysonXxxError`.
21/// Every `DatabaseError`/`TableError` variant maps onto exactly one of these.
22pub mod code {
23    pub const VALIDATION: &str = "Validation";
24    pub const UNIQUE_VIOLATION: &str = "UniqueViolation";
25    pub const PENDING_CONFLICT: &str = "PendingConflict";
26    pub const NOT_FOUND: &str = "NotFound";
27    pub const SCHEMA: &str = "Schema";
28    pub const PARTITION: &str = "Partition";
29    pub const RELATION_VIOLATION: &str = "RelationViolation";
30    pub const RELATION_RESTRICT: &str = "RelationRestrict";
31    pub const CIPHER: &str = "Cipher";
32    pub const LOCKED: &str = "Locked";
33    pub const LOCK_LOST: &str = "LockLost";
34    pub const SUSPICIOUS_LOCK_FILE: &str = "SuspiciousLockFile";
35    pub const READ_ONLY: &str = "ReadOnly";
36    pub const FIELD_IN_USE: &str = "FieldInUse";
37    pub const CATALOG: &str = "Catalog";
38    pub const TXN: &str = "Txn";
39    pub const INDEX_MISMATCH: &str = "IndexMismatch";
40    pub const LOG_REPLACED: &str = "LogReplaced";
41    pub const CORRUPT_LOG: &str = "CorruptLog";
42    pub const IMAGE_CLASH: &str = "ImageClash";
43    pub const IMAGE_TOO_LARGE: &str = "ImageTooLarge";
44    pub const TEMPORARY_FILE: &str = "TemporaryFile";
45    pub const IO: &str = "Io";
46    pub const INVALID_JSON: &str = "InvalidJson";
47    pub const CLOSED: &str = "Closed";
48}
49
50fn envelope(code: &str, message: String, fields: Map<String, Value>) -> Value {
51    let mut object = Map::new();
52    object.insert("envelopeVersion".to_string(), json!(ENVELOPE_VERSION));
53    object.insert("code".to_string(), json!(code));
54    object.insert("message".to_string(), json!(message));
55    for (key, value) in fields {
56        object.insert(key, value);
57    }
58    Value::Object(object)
59}
60
61fn no_fields() -> Map<String, Value> {
62    Map::new()
63}
64
65fn fields(pairs: Value) -> Map<String, Value> {
66    match pairs {
67        Value::Object(map) => map,
68        _ => Map::new(),
69    }
70}
71
72fn describe_cipher_error(error: &HaysonCipherError) -> Value {
73    envelope(
74        code::CIPHER,
75        error.to_string(),
76        fields(json!({
77            "table": error.table,
78            "field": error.field,
79            "reason": error.reason,
80            "keyId": error.key_id,
81        })),
82    )
83}
84
85fn describe_locked_error(error: &LockedError) -> Value {
86    // NOTE: `subject` is the database directory, not the lock file — `DirLock::acquire` takes the
87    // parent of the path it was given before building this error.
88    let dir = error.subject.display().to_string();
89    let holder = error.holder.as_ref().map(|holder| {
90        json!({
91            "owner": holder.owner,
92            "pid": holder.pid,
93            "host": holder.host,
94            "startedAt": holder.started_at,
95            "heartbeatAt": holder.heartbeat_at,
96        })
97    });
98    envelope(
99        code::LOCKED,
100        error.to_string(),
101        fields(json!({ "dir": dir, "holder": holder, "waitedMs": error.waited_ms })),
102    )
103}
104
105/// `table` is the name the call was made against — `TableError` itself carries one only on the
106/// variants built from a `HaysonXxxError`, and even then not on `Io`.
107pub fn describe_table_error(table: &str, error: &TableError) -> Value {
108    let message = error.to_string();
109    match error {
110        TableError::Validation(inner) => envelope(
111            code::VALIDATION,
112            message,
113            fields(json!({
114                "table": inner.table,
115                "issues": inner
116                    .issues
117                    .iter()
118                    .map(|issue| json!({ "field": issue.field, "reason": issue.reason }))
119                    .collect::<Vec<_>>(),
120            })),
121        ),
122        TableError::Unique(inner) => envelope(
123            code::UNIQUE_VIOLATION,
124            message,
125            fields(json!({ "table": inner.table, "field": inner.field, "holder": inner.holder })),
126        ),
127        TableError::Conflict(inner) => envelope(
128            code::PENDING_CONFLICT,
129            message,
130            fields(json!({ "table": inner.table, "key": inner.key, "fields": inner.fields })),
131        ),
132        TableError::NotFound(inner) => envelope(
133            code::NOT_FOUND,
134            message,
135            fields(json!({ "table": inner.table, "key": inner.key })),
136        ),
137        TableError::Schema(_) => envelope(code::SCHEMA, message, fields(json!({ "table": table }))),
138        TableError::Partition(inner) => envelope(
139            code::PARTITION,
140            message,
141            fields(json!({ "table": inner.table, "field": inner.field, "reason": inner.reason })),
142        ),
143        TableError::Relation(inner) => envelope(
144            code::RELATION_VIOLATION,
145            message,
146            fields(json!({
147                "relation": inner.relation,
148                "table": inner.table,
149                "field": inner.field,
150                "value": inner.value,
151            })),
152        ),
153        TableError::RelationRestrict(inner) => envelope(
154            code::RELATION_RESTRICT,
155            message,
156            fields(json!({
157                "relation": inner.relation,
158                "table": inner.table,
159                "key": inner.key,
160                "referencingTable": inner.referencing_table,
161                "referencingField": inner.referencing_field,
162                "referencing": inner.referencing,
163            })),
164        ),
165        TableError::Cipher(inner) => describe_cipher_error(inner),
166        TableError::Io(inner) => describe_io_error(inner),
167    }
168}
169
170/// `checkpoint::restore_or_rebuild` reports a snapshot paired with a different log through
171/// `io::Error::other`, so the typed refusal survives only as the boxed source of that io error.
172/// Without this the shim sees `Io` and cannot tell the index-mismatch refusal from a disk failure.
173fn index_mismatch_of(error: &io::Error) -> Option<&HaysonIndexMismatchError> {
174    error.get_ref()?.downcast_ref::<HaysonIndexMismatchError>()
175}
176
177fn corrupt_log_of(error: &io::Error) -> Option<&HaysonCorruptLogError> {
178    error.get_ref()?.downcast_ref::<HaysonCorruptLogError>()
179}
180
181fn image_clash_of(error: &io::Error) -> Option<&HaysonImageClashError> {
182    error.get_ref()?.downcast_ref::<HaysonImageClashError>()
183}
184
185fn image_too_large_of(error: &io::Error) -> Option<&HaysonImageTooLargeError> {
186    error.get_ref()?.downcast_ref::<HaysonImageTooLargeError>()
187}
188
189fn log_replaced_of(error: &io::Error) -> Option<&HaysonLogReplacedError> {
190    error.get_ref()?.downcast_ref::<HaysonLogReplacedError>()
191}
192
193/// `atomic::open_temporary` refuses a `.tmp` path it could not claim through an `io::Error` that
194/// boxes the typed refusal, so the path and the reason survive only as that boxed source. Without
195/// this the shim sees `Io` — or, on a catalog write, `Catalog` — and the caller loses the one file
196/// it has to remove before retrying.
197fn temporary_file_of(error: &io::Error) -> Option<&AtomicTemporaryFileError> {
198    AtomicTemporaryFileError::downcast(error)
199}
200
201pub fn describe_io_error(error: &io::Error) -> Value {
202    if let Some(inner) = temporary_file_of(error) {
203        return envelope(
204            code::TEMPORARY_FILE,
205            error.to_string(),
206            fields(json!({
207                "path": inner.path.display().to_string(),
208                "reason": inner.reason,
209            })),
210        );
211    }
212    if let Some(inner) = corrupt_log_of(error) {
213        return envelope(
214            code::CORRUPT_LOG,
215            error.to_string(),
216            fields(json!({ "path": inner.path, "offset": inner.offset, "reason": inner.reason })),
217        );
218    }
219    if let Some(inner) = image_too_large_of(error) {
220        return envelope(
221            code::IMAGE_TOO_LARGE,
222            error.to_string(),
223            fields(json!({ "bytes": inner.bytes, "maxBytes": inner.max_bytes })),
224        );
225    }
226    if let Some(inner) = image_clash_of(error) {
227        return envelope(
228            code::IMAGE_CLASH,
229            error.to_string(),
230            fields(json!({ "physicalPath": inner.physical_path })),
231        );
232    }
233    if let Some(inner) = log_replaced_of(error) {
234        return envelope(
235            code::LOG_REPLACED,
236            error.to_string(),
237            fields(json!({ "path": inner.path })),
238        );
239    }
240    if let Some(inner) = index_mismatch_of(error) {
241        return envelope(
242            code::INDEX_MISMATCH,
243            error.to_string(),
244            fields(json!({
245                "indexPath": inner.path,
246                "logPath": inner.log_path,
247                "watermark": inner.watermark,
248                "expectedHash": inner.expected_hash,
249                "actualHash": inner.actual_hash,
250            })),
251        );
252    }
253    envelope(
254        code::IO,
255        error.to_string(),
256        fields(json!({ "kind": format!("{:?}", error.kind()) })),
257    )
258}
259
260/// The errno name a host raised in a language whose IO errors carry one — Node reports it as
261/// `error.code`, and a caller that means to tell "this file is gone" from "this file is unreadable"
262/// has nothing else to go on. `None` for a kind with no single portable name, in which case the
263/// envelope simply omits it rather than guessing.
264fn errno_name_of(error: &io::Error) -> Option<&'static str> {
265    match error.kind() {
266        io::ErrorKind::NotFound => Some("ENOENT"),
267        io::ErrorKind::PermissionDenied => Some("EACCES"),
268        _ => None,
269    }
270}
271
272/// A [`describe_io_error`] that knows which file failed. `io::Error` carries no path, so only a
273/// call site that kept one can produce this — today `DatabaseError::Log`, raised by the readonly
274/// open probing the logs it is about to take on.
275fn describe_log_io_error(path: &Path, error: &io::Error) -> Value {
276    let mut described = fields(json!({
277        "kind": format!("{:?}", error.kind()),
278        "path": path.display().to_string(),
279    }));
280    if let Some(name) = errno_name_of(error) {
281        described.insert("errnoCode".to_string(), json!(name));
282    }
283    envelope(code::IO, format!("{error}, open \"{}\"", path.display()), described)
284}
285
286/// Public because a binding raises `TxnError::AlreadyCommitted` itself: a unit of work handed to
287/// the engine is consumed there, so a second call on the same host-side handle never reaches the
288/// engine to be refused by it.
289pub fn describe_txn_error(error: &TxnError) -> Value {
290    match error {
291        TxnError::Table(name, inner) => describe_table_error(name, inner),
292        TxnError::Io(inner) => describe_io_error(inner),
293        TxnError::UnknownTable(name) => envelope(code::NOT_FOUND, error.to_string(), fields(json!({ "table": name }))),
294        TxnError::AlreadyCommitted | TxnError::JournalPending(_) => envelope(code::TXN, error.to_string(), no_fields()),
295    }
296}
297
298pub fn describe_database_error(error: &DatabaseError) -> Value {
299    let message = error.to_string();
300    match error {
301        DatabaseError::Lock(DirLockError::Locked(inner)) => describe_locked_error(inner),
302        DatabaseError::Lock(DirLockError::Lost(path)) => envelope(
303            code::LOCK_LOST,
304            message,
305            fields(json!({ "lockPath": path.display().to_string() })),
306        ),
307        DatabaseError::Lock(DirLockError::SuspiciousLockFile(path)) => envelope(
308            code::SUSPICIOUS_LOCK_FILE,
309            message,
310            fields(json!({ "lockPath": path.display().to_string() })),
311        ),
312        DatabaseError::Lock(DirLockError::Io(inner)) => describe_io_error(inner),
313        DatabaseError::Schema(_) => envelope(code::SCHEMA, message, no_fields()),
314        DatabaseError::ReadOnly { dir, operation } => envelope(
315            code::READ_ONLY,
316            message,
317            fields(json!({ "dir": dir.display().to_string(), "operation": operation })),
318        ),
319        DatabaseError::FieldInUse { table, field, records } => envelope(
320            code::FIELD_IN_USE,
321            message,
322            fields(json!({ "table": table, "field": field, "records": records })),
323        ),
324        DatabaseError::Catalog(_) => envelope(code::CATALOG, message, no_fields()),
325        DatabaseError::Io(inner) => describe_io_error(inner),
326        DatabaseError::Log(path, inner) => describe_log_io_error(path, inner),
327        DatabaseError::Table(name, inner) => describe_table_error(name, inner),
328        DatabaseError::Txn(inner) => describe_txn_error(inner),
329        DatabaseError::Cipher(inner) => describe_cipher_error(inner),
330    }
331}
332
333pub fn describe_migrate_format1_error(error: &MigrateFormat1Error) -> Value {
334    let message = error.to_string();
335    match error {
336        MigrateFormat1Error::Schema(_) | MigrateFormat1Error::Write(_) => envelope(code::SCHEMA, message, no_fields()),
337        MigrateFormat1Error::Io(inner) => describe_io_error(inner),
338        MigrateFormat1Error::NotADirectory(path)
339        | MigrateFormat1Error::UnreadableMarker(path, _)
340        | MigrateFormat1Error::UnknownMarker(path, _)
341        | MigrateFormat1Error::NoSchemaFiles(path) => envelope(
342            code::SCHEMA,
343            message,
344            fields(json!({ "path": path.display().to_string() })),
345        ),
346    }
347}
348
349pub fn describe_invalid_json(what: &str, error: &serde_json::Error) -> Value {
350    envelope(
351        code::INVALID_JSON,
352        format!("{what} is not valid JSON: {error}"),
353        fields(json!({ "argument": what })),
354    )
355}
356
357pub fn describe_unknown_table(table: &str, dir: &str) -> Value {
358    envelope(
359        code::NOT_FOUND,
360        format!("table \"{table}\" does not exist in \"{dir}\""),
361        fields(json!({ "table": table, "dir": dir })),
362    )
363}
364
365pub fn describe_closed(operation: &str) -> Value {
366    envelope(
367        code::CLOSED,
368        format!("{operation} was called after the database was closed"),
369        fields(json!({ "operation": operation })),
370    )
371}
372
373/// Free-form refusals raised by this binding itself (a malformed `open` option, an unusable key).
374pub fn describe_schema(message: String) -> Value {
375    envelope(code::SCHEMA, message, no_fields())
376}
377
378pub fn describe_cipher_config(message: String) -> Value {
379    envelope(code::CIPHER, message, fields(json!({ "table": "", "field": "" })))
380}
381
382#[cfg(test)]
383mod tests {
384    use hayson_engine::errors::{
385        HaysonNotFoundError, HaysonPartitionError, HaysonSchemaError, HaysonUniqueViolationError,
386        HaysonValidationError, ValidationIssue,
387    };
388    use hayson_engine::lock::LockHolder;
389    use std::path::PathBuf;
390
391    use super::*;
392
393    fn scratch_dir(prefix: &str) -> PathBuf {
394        let dir = std::env::temp_dir().join(format!(
395            "{prefix}{}-{}",
396            std::process::id(),
397            std::time::SystemTime::now()
398                .duration_since(std::time::UNIX_EPOCH)
399                .unwrap()
400                .as_nanos()
401        ));
402        std::fs::create_dir_all(&dir).unwrap();
403        dir
404    }
405
406    fn code_of(value: &Value) -> &str {
407        value.get("code").and_then(Value::as_str).unwrap()
408    }
409
410    #[test]
411    fn a_validation_error_carries_every_issue_the_shim_needs_to_rebuild_it() {
412        let error = TableError::Validation(HaysonValidationError {
413            table: "users".into(),
414            issues: vec![ValidationIssue {
415                field: "name".into(),
416                reason: "is required".into(),
417            }],
418        });
419
420        let described = describe_table_error("users", &error);
421
422        assert_eq!(code_of(&described), code::VALIDATION);
423        assert_eq!(described["table"], json!("users"));
424        assert_eq!(
425            described["issues"],
426            json!([{ "field": "name", "reason": "is required" }])
427        );
428        assert_eq!(described["envelopeVersion"], json!(ENVELOPE_VERSION));
429        assert_eq!(described["message"], json!(error.to_string()));
430    }
431
432    #[test]
433    fn a_unique_violation_names_the_field_and_the_key_already_holding_it() {
434        let error = TableError::Unique(HaysonUniqueViolationError {
435            table: "users".into(),
436            field: "email".into(),
437            holder: "u1".into(),
438        });
439
440        let described = describe_table_error("users", &error);
441
442        assert_eq!(code_of(&described), code::UNIQUE_VIOLATION);
443        assert_eq!(described["field"], json!("email"));
444        assert_eq!(described["holder"], json!("u1"));
445    }
446
447    #[test]
448    fn a_not_found_error_keeps_the_table_and_key_apart_from_the_message() {
449        let error = TableError::NotFound(HaysonNotFoundError {
450            table: "users".into(),
451            key: "u9".into(),
452        });
453
454        let described = describe_table_error("users", &error);
455
456        assert_eq!(code_of(&described), code::NOT_FOUND);
457        assert_eq!(described["key"], json!("u9"));
458    }
459
460    #[test]
461    fn a_partition_error_is_tagged_apart_from_a_plain_schema_rejection() {
462        let partition = TableError::Partition(HaysonPartitionError::new("events", "day", "is empty"));
463        let schema = TableError::Schema(HaysonSchemaError("no".into()));
464
465        assert_eq!(code_of(&describe_table_error("events", &partition)), code::PARTITION);
466        assert_eq!(code_of(&describe_table_error("events", &schema)), code::SCHEMA);
467    }
468
469    #[test]
470    fn a_cipher_error_carries_the_key_id_it_could_not_use() {
471        let error = TableError::Cipher(Box::new(
472            HaysonCipherError::new("secrets", "token", "cannot be opened").with_key_id("k2"),
473        ));
474
475        let described = describe_table_error("secrets", &error);
476
477        assert_eq!(code_of(&described), code::CIPHER);
478        assert_eq!(described["keyId"], json!("k2"));
479        assert_eq!(described["field"], json!("token"));
480    }
481
482    #[test]
483    fn a_locked_database_reports_the_directory_the_holder_and_how_long_we_waited() {
484        let error = DatabaseError::Lock(DirLockError::Locked(LockedError {
485            // `DirLock::acquire` stores the directory here, not the `.hayson.lock` inside it.
486            subject: PathBuf::from("/data/db"),
487            holder: Some(LockHolder {
488                owner: "0f1e2d3c".into(),
489                pid: Some(42),
490                host: Some("box".into()),
491                started_at: 10,
492                heartbeat_at: 20,
493            }),
494            waited_ms: 250,
495        }));
496
497        let described = describe_database_error(&error);
498
499        assert_eq!(code_of(&described), code::LOCKED);
500        assert_eq!(described["dir"], json!("/data/db"));
501        assert_eq!(described["waitedMs"], json!(250));
502        assert_eq!(described["holder"]["owner"], json!("0f1e2d3c"));
503        assert_eq!(described["holder"]["pid"], json!(42));
504        assert_eq!(described["holder"]["startedAt"], json!(10));
505    }
506
507    #[test]
508    fn a_lock_taken_over_by_another_writer_reports_the_lock_path_under_its_own_code() {
509        let error = DatabaseError::Lock(DirLockError::Lost(PathBuf::from("/data/db/.hayson.lock")));
510
511        let described = describe_database_error(&error);
512
513        assert_eq!(code_of(&described), code::LOCK_LOST);
514        assert_eq!(described["lockPath"], json!("/data/db/.hayson.lock"));
515    }
516
517    #[test]
518    fn a_symlink_planted_at_the_lock_path_reports_the_lock_path_under_its_own_code() {
519        let error = DatabaseError::Lock(DirLockError::SuspiciousLockFile(PathBuf::from("/data/db/.hayson.lock")));
520
521        let described = describe_database_error(&error);
522
523        assert_eq!(code_of(&described), code::SUSPICIOUS_LOCK_FILE);
524        assert_eq!(described["lockPath"], json!("/data/db/.hayson.lock"));
525    }
526
527    #[test]
528    fn a_readonly_refusal_is_told_apart_from_a_genuine_schema_error() {
529        let readonly = DatabaseError::ReadOnly {
530            dir: PathBuf::from("/data/db"),
531            operation: "createTable".into(),
532        };
533        let genuine = DatabaseError::Schema(HaysonSchemaError("field \"id\" has no type".into()));
534
535        let described = describe_database_error(&readonly);
536        assert_eq!(code_of(&described), code::READ_ONLY);
537        assert_eq!(described["operation"], json!("createTable"));
538        assert_eq!(described["dir"], json!("/data/db"));
539
540        assert_eq!(code_of(&describe_database_error(&genuine)), code::SCHEMA);
541    }
542
543    #[test]
544    fn a_residual_field_refusal_is_told_apart_from_a_plain_catalog_error() {
545        let in_use = DatabaseError::FieldInUse {
546            table: "users".into(),
547            field: "name".into(),
548            records: 3,
549        };
550        let plain = DatabaseError::Catalog("table \"ghost\" does not exist in \"/data/db\"".into());
551
552        let described = describe_database_error(&in_use);
553        assert_eq!(code_of(&described), code::FIELD_IN_USE);
554        assert_eq!(described["table"], json!("users"));
555        assert_eq!(described["field"], json!("name"));
556        assert_eq!(described["records"], json!(3));
557
558        assert_eq!(code_of(&describe_database_error(&plain)), code::CATALOG);
559    }
560
561    #[test]
562    fn a_table_scoped_database_error_is_described_as_its_inner_table_error() {
563        let error = DatabaseError::Table(
564            "users".into(),
565            TableError::NotFound(HaysonNotFoundError {
566                table: "users".into(),
567                key: "u9".into(),
568            }),
569        );
570
571        assert_eq!(code_of(&describe_database_error(&error)), code::NOT_FOUND);
572    }
573
574    #[test]
575    fn an_unknown_table_inside_a_unit_of_work_is_reported_as_not_found() {
576        let error = DatabaseError::Txn(TxnError::UnknownTable("ghost".into()));
577
578        let described = describe_database_error(&error);
579
580        assert_eq!(code_of(&described), code::NOT_FOUND);
581        assert_eq!(described["table"], json!("ghost"));
582    }
583
584    #[test]
585    fn an_io_failure_keeps_its_kind_so_the_shim_can_tell_missing_from_denied() {
586        let error = DatabaseError::Io(io::Error::new(io::ErrorKind::PermissionDenied, "nope"));
587
588        let described = describe_database_error(&error);
589
590        assert_eq!(code_of(&described), code::IO);
591        assert_eq!(described["kind"], json!("PermissionDenied"));
592    }
593
594    #[test]
595    fn an_io_failure_the_engine_could_name_a_file_for_carries_the_path_and_the_errno_name() {
596        let error = DatabaseError::Log(
597            PathBuf::from("/data/db/notes/note.jsonl"),
598            io::Error::from(io::ErrorKind::NotFound),
599        );
600
601        let described = describe_database_error(&error);
602
603        assert_eq!(code_of(&described), code::IO);
604        assert_eq!(described["path"], json!("/data/db/notes/note.jsonl"));
605        assert_eq!(described["errnoCode"], json!("ENOENT"));
606    }
607
608    #[test]
609    fn an_io_kind_with_no_portable_errno_name_leaves_the_field_out_rather_than_guessing() {
610        let error = DatabaseError::Log(
611            PathBuf::from("/data/db/notes.jsonl"),
612            io::Error::new(io::ErrorKind::InvalidData, "garbled"),
613        );
614
615        let described = describe_database_error(&error);
616
617        assert_eq!(described["path"], json!("/data/db/notes.jsonl"));
618        assert!(described.get("errnoCode").is_none(), "{described}");
619    }
620
621    #[test]
622    fn a_read_that_failed_to_decrypt_arrives_typed_with_the_key_id_the_flattened_text_used_to_lose() {
623        let error = TableError::Cipher(Box::new(
624            HaysonCipherError::new("secrets", "token", "was written with key \"k1\", which is not on hand")
625                .with_key_id("k1"),
626        ));
627
628        let described = describe_table_error("secrets", &error);
629
630        assert_eq!(code_of(&described), code::CIPHER);
631        assert_eq!(described["table"], json!("secrets"));
632        assert_eq!(described["field"], json!("token"));
633        assert_eq!(described["keyId"], json!("k1"));
634    }
635
636    #[test]
637    fn an_io_failure_on_a_read_stays_an_io_failure_now_that_nothing_reads_its_text() {
638        let corrupt = TableError::Io(io::Error::new(
639            io::ErrorKind::InvalidData,
640            "log \"a.jsonl\" is corrupt at offset 12",
641        ));
642
643        assert_eq!(code_of(&describe_table_error("notes", &corrupt)), code::IO);
644    }
645
646    #[test]
647    fn a_search_against_a_table_with_no_fulltext_field_arrives_as_a_typed_schema_refusal() {
648        let error = TableError::Schema(HaysonSchemaError(
649            "table \"users\" has no field marked \"fulltext\": true — search is not available".into(),
650        ));
651
652        let described = describe_table_error("users", &error);
653
654        assert_eq!(code_of(&described), code::SCHEMA);
655        assert_eq!(described["table"], json!("users"));
656    }
657
658    #[test]
659    fn a_write_onto_a_replaced_log_travels_under_its_own_code_with_the_path() {
660        let error = TableError::Io(io::Error::other(HaysonLogReplacedError {
661            path: "/data/db/users.jsonl".into(),
662        }));
663
664        let described = describe_table_error("users", &error);
665
666        assert_eq!(code_of(&described), code::LOG_REPLACED);
667        assert_eq!(described["path"], json!("/data/db/users.jsonl"));
668        assert_eq!(described["message"], json!(error.to_string()));
669    }
670
671    #[test]
672    fn a_corrupt_log_line_travels_under_its_own_code_with_file_and_offset() {
673        let error = DatabaseError::Io(io::Error::new(
674            io::ErrorKind::InvalidData,
675            HaysonCorruptLogError {
676                path: "/data/db/users.jsonl".into(),
677                offset: 1234,
678                reason: "line is not valid JSON".into(),
679            },
680        ));
681
682        let described = describe_database_error(&error);
683
684        assert_eq!(code_of(&described), code::CORRUPT_LOG);
685        assert_eq!(described["path"], json!("/data/db/users.jsonl"));
686        assert_eq!(described["offset"], json!(1234));
687        assert_eq!(described["reason"], json!("line is not valid JSON"));
688    }
689
690    #[test]
691    fn an_oversize_image_travels_under_its_own_code_with_both_sizes() {
692        let error = TableError::Io(io::Error::new(
693            io::ErrorKind::InvalidData,
694            HaysonImageTooLargeError {
695                bytes: 900,
696                max_bytes: 500,
697            },
698        ));
699
700        let described = describe_table_error("docs", &error);
701
702        assert_eq!(code_of(&described), code::IMAGE_TOO_LARGE);
703        assert_eq!(described["bytes"], json!(900));
704        assert_eq!(described["maxBytes"], json!(500));
705    }
706
707    #[test]
708    fn an_image_name_clash_travels_under_its_own_code_with_the_physical_path() {
709        let error = TableError::Io(io::Error::new(
710            io::ErrorKind::InvalidData,
711            HaysonImageClashError {
712                physical_path: "ab12.png".into(),
713            },
714        ));
715
716        let described = describe_table_error("docs", &error);
717
718        assert_eq!(code_of(&described), code::IMAGE_CLASH);
719        assert_eq!(described["physicalPath"], json!("ab12.png"));
720    }
721
722    #[test]
723    fn a_refused_index_snapshot_travels_under_its_own_code_with_both_paths_and_the_watermark() {
724        let error = DatabaseError::Io(io::Error::other(HaysonIndexMismatchError {
725            path: "/data/db/users.idx".into(),
726            log_path: "/data/db/users.jsonl".into(),
727            watermark: 397,
728            expected_hash: "9f2c000000000000".into(),
729            actual_hash: "4b1e000000000000".into(),
730        }));
731
732        let described = describe_database_error(&error);
733
734        assert_eq!(code_of(&described), code::INDEX_MISMATCH);
735        assert_eq!(described["indexPath"], json!("/data/db/users.idx"));
736        assert_eq!(described["logPath"], json!("/data/db/users.jsonl"));
737        assert_eq!(described["watermark"], json!(397));
738        assert_eq!(described["expectedHash"], json!("9f2c000000000000"));
739        assert_eq!(described["actualHash"], json!("4b1e000000000000"));
740        assert_eq!(described["message"], json!(error.to_string()));
741    }
742
743    #[test]
744    fn a_temporary_path_that_could_not_be_claimed_travels_under_its_own_code_with_path_and_reason() {
745        let dir = scratch_dir("hayson-envelope-temporary-");
746        // A directory on the .tmp path: open_exclusive reports AlreadyExists and remove_file cannot
747        // clear it, which is the shape of the refusal a catalog write hits on EISDIR.
748        let temporary = dir.join("hayson.json.tmp");
749        std::fs::create_dir(&temporary).unwrap();
750        let refusal = hayson_engine::atomic::open_temporary(&temporary, None).unwrap_err();
751        let message = refusal.to_string();
752        let error = DatabaseError::Io(refusal);
753
754        let described = describe_database_error(&error);
755        std::fs::remove_dir_all(&dir).unwrap();
756
757        assert_eq!(code_of(&described), code::TEMPORARY_FILE);
758        assert_eq!(described["path"], json!(temporary.display().to_string()));
759        assert_eq!(described["reason"], json!("is in the way and could not be cleared, so nothing on disk was changed — remove whatever holds that path and retry"));
760        assert_eq!(described["message"], json!(message));
761    }
762
763    #[test]
764    fn an_io_error_that_boxes_nothing_typed_is_still_reported_as_io() {
765        let error = io::Error::other("snapshot \"a.idx\" claims watermark and schema match the log");
766
767        assert_eq!(code_of(&describe_io_error(&error)), code::IO);
768    }
769}