Skip to main content

hayson_binding_shared/
options.rs

1use std::collections::HashMap;
2
3use std::time::Duration;
4
5use hayson_engine::catalog::CatalogCompaction;
6use hayson_engine::crypto::{CipherOptions, MissingKeyPolicy};
7use hayson_engine::database::{
8    BackupOptions, FollowOption, LayoutKind, LayoutMigrationOptions, LayoutOptions, LockMode, OpenOptions,
9    RestoreOptions, VerifyOptions,
10};
11use hayson_engine::lock::{GraceServed, LockOptions};
12use serde_json::Value;
13
14/// Rejection of an `open()` options document, before the engine is ever touched.
15#[derive(Debug, PartialEq, Eq)]
16pub enum OptionsError {
17    /// A malformed option: wrong JSON type, unknown enum member, out-of-range number.
18    Shape(String),
19    /// Unusable key material — reported to JS as a cipher error, not a schema one.
20    Key(String),
21}
22
23fn shape<T>(message: impl Into<String>) -> Result<T, OptionsError> {
24    Err(OptionsError::Shape(message.into()))
25}
26
27fn as_object<'a>(value: &'a Value, what: &str) -> Result<&'a serde_json::Map<String, Value>, OptionsError> {
28    match value.as_object() {
29        Some(object) => Ok(object),
30        None => shape(format!("\"{what}\" must be a JSON object")),
31    }
32}
33
34fn optional_bool(object: &serde_json::Map<String, Value>, key: &str) -> Result<Option<bool>, OptionsError> {
35    match object.get(key) {
36        None | Some(Value::Null) => Ok(None),
37        Some(Value::Bool(value)) => Ok(Some(*value)),
38        Some(_) => shape(format!("\"{key}\" must be a boolean")),
39    }
40}
41
42fn optional_u64(object: &serde_json::Map<String, Value>, key: &str) -> Result<Option<u64>, OptionsError> {
43    match object.get(key) {
44        None | Some(Value::Null) => Ok(None),
45        Some(Value::Number(number)) => match number.as_u64() {
46            Some(value) => Ok(Some(value)),
47            None => shape(format!("\"{key}\" must be a non-negative whole number")),
48        },
49        Some(_) => shape(format!("\"{key}\" must be a number")),
50    }
51}
52
53fn optional_i64(object: &serde_json::Map<String, Value>, key: &str) -> Result<Option<i64>, OptionsError> {
54    match object.get(key) {
55        None | Some(Value::Null) => Ok(None),
56        Some(Value::Number(number)) => match number.as_i64() {
57            Some(value) => Ok(Some(value)),
58            None => shape(format!("\"{key}\" must be a whole number")),
59        },
60        Some(_) => shape(format!("\"{key}\" must be a number")),
61    }
62}
63
64fn optional_string(object: &serde_json::Map<String, Value>, key: &str) -> Result<Option<String>, OptionsError> {
65    match object.get(key) {
66        None | Some(Value::Null) => Ok(None),
67        Some(Value::String(value)) => Ok(Some(value.clone())),
68        Some(_) => shape(format!("\"{key}\" must be a string")),
69    }
70}
71
72/// `lock` in the shapes the TS `OpenOptions` takes (`boolean | LockOptions`): an object of lease
73/// tuning, or `false` to open without taking the writer lock at all — mutual exclusion between
74/// writers is then not enforced, which is the whole point and the whole danger of the option.
75/// `true` is TS's "lock the usual way" and resolves to the engine's defaults, not to skipping.
76fn parse_lock(value: &Value) -> Result<LockMode, OptionsError> {
77    match value {
78        Value::Bool(false) => Ok(LockMode::Skip),
79        Value::Bool(true) => Ok(LockMode::Enabled(LockOptions::default())),
80        Value::Object(object) => Ok(LockMode::Enabled(LockOptions {
81            stale_after_ms: optional_u64(object, "staleAfterMs")?,
82            heartbeat_ms: optional_u64(object, "heartbeatMs")?,
83            timeout_ms: optional_u64(object, "timeoutMs")?,
84            retry_interval_ms: optional_u64(object, "retryIntervalMs")?,
85            grace_served: parse_grace_served(object)?,
86        })),
87        _ => shape("\"lock\" must be a boolean or an object of lock options"),
88    }
89}
90
91/// `graceServed` — the lease a host has already challenged and waited the hand-over grace out on,
92/// so that the open it precedes reclaims that lease without the engine sleeping inside a call the
93/// host is waiting on. Not part of the public TS `LockOptions`: the binding layer synthesises it
94/// between two attempts of its own, off the `holder` its previous refusal named.
95///
96/// A token naming a lease that has since moved is not an error — it simply buys nothing, and the
97/// ordinary hand-over runs instead. Only its shape is judged here.
98fn parse_grace_served(object: &serde_json::Map<String, Value>) -> Result<Option<GraceServed>, OptionsError> {
99    let served = match object.get("graceServed") {
100        None | Some(Value::Null) => return Ok(None),
101        Some(value) => as_object(value, "graceServed")?,
102    };
103    let Some(owner) = optional_string(served, "owner")? else {
104        return shape("\"graceServed\" must name the \"owner\" whose grace it waited out");
105    };
106    let Some(heartbeat_at) = optional_i64(served, "heartbeatAt")? else {
107        return shape("\"graceServed\" must name the \"heartbeatAt\" whose grace it waited out");
108    };
109    Ok(GraceServed::parse(&owner, heartbeat_at))
110}
111
112/// `follow` in the three shapes the TS `OpenOptions` takes: `false` to never catch up unprompted,
113/// `true` for the engine's default interval, or `{ intervalMs }` for a custom one. Absent is not
114/// handled here — it means "resolve by `readonly`" and never reaches this function.
115fn parse_follow(value: &Value) -> Result<FollowOption, OptionsError> {
116    match value {
117        Value::Bool(false) => Ok(FollowOption::Off),
118        Value::Bool(true) => Ok(FollowOption::Every(Duration::ZERO)),
119        Value::Object(object) => match optional_u64(object, "intervalMs")? {
120            Some(interval_ms) => Ok(FollowOption::Every(Duration::from_millis(interval_ms))),
121            None => Ok(FollowOption::Every(Duration::ZERO)),
122        },
123        _ => shape("\"follow\" must be a boolean or an object with \"intervalMs\""),
124    }
125}
126
127/// `compaction` in the two shapes the TS `OpenOptions` takes: `false` to never rewrite a log
128/// unprompted, or `{ deadBytesRatio, minDeadBytes }` to set both thresholds. Absent is not handled
129/// here — it means "leave it to the catalog" and never reaches this function.
130fn parse_compaction(value: &Value) -> Result<CatalogCompaction, OptionsError> {
131    match value {
132        Value::Bool(false) => Ok(CatalogCompaction::Disabled),
133        Value::Object(object) => {
134            let ratio = match object.get("deadBytesRatio") {
135                None | Some(Value::Null) => None,
136                Some(Value::Number(number)) => number.as_f64(),
137                Some(_) => return shape("\"deadBytesRatio\" must be a number"),
138            };
139            let Some(dead_bytes_ratio) = ratio.filter(|ratio| *ratio > 0.0 && *ratio <= 1.0) else {
140                return shape("\"deadBytesRatio\" must be a number greater than 0 and at most 1");
141            };
142            let min_dead_bytes = optional_u64(object, "minDeadBytes")?.unwrap_or(0);
143            Ok(CatalogCompaction::Enabled {
144                dead_bytes_ratio,
145                min_dead_bytes,
146            })
147        }
148        _ => shape("\"compaction\" must be false or an object of compaction thresholds"),
149    }
150}
151
152fn parse_layout_kind(raw: &str) -> Result<LayoutKind, OptionsError> {
153    match raw {
154        "flat" => Ok(LayoutKind::Flat),
155        "nested" => Ok(LayoutKind::Nested),
156        other => shape(format!("\"layout\" must be \"flat\" or \"nested\" — got \"{other}\"")),
157    }
158}
159
160/// The `layout`/`metadataFile`/`manifest` triple, passed on unresolved: whether the two file names
161/// agree, and whether the requested arrangement matches the one on disk, is the engine's call, so
162/// both refusals read the same however a caller reaches them.
163fn parse_layout(object: &serde_json::Map<String, Value>) -> Result<LayoutOptions, OptionsError> {
164    Ok(LayoutOptions {
165        kind: match optional_string(object, "layout")? {
166            Some(raw) => Some(parse_layout_kind(&raw)?),
167            None => None,
168        },
169        metadata_file: optional_string(object, "metadataFile")?,
170        manifest: optional_string(object, "manifest")?,
171    })
172}
173
174fn parse_missing_key_policy(raw: &str) -> Result<MissingKeyPolicy, OptionsError> {
175    match raw {
176        "throw" => Ok(MissingKeyPolicy::Throw),
177        "omit" => Ok(MissingKeyPolicy::Omit),
178        "raw" => Ok(MissingKeyPolicy::Raw),
179        other => shape(format!(
180            "\"onMissingKey\" must be one of \"throw\", \"omit\", \"raw\" — got \"{other}\""
181        )),
182    }
183}
184
185/// Decodes one key of the `cypher.keys` map. `encoding` is the document-wide `keyEncoding`.
186fn decode_key(id: &str, raw: &str, encoding: KeyEncoding) -> Result<Vec<u8>, OptionsError> {
187    let decoded = match encoding {
188        KeyEncoding::Base64 => decode_base64(raw),
189        KeyEncoding::Hex => decode_hex(raw),
190    };
191    decoded.ok_or_else(|| OptionsError::Key(format!("key \"{id}\" is not valid {}", encoding.as_str())))
192}
193
194#[derive(Debug, Clone, Copy, PartialEq, Eq)]
195pub enum KeyEncoding {
196    Base64,
197    Hex,
198}
199
200impl KeyEncoding {
201    fn as_str(self) -> &'static str {
202        match self {
203            KeyEncoding::Base64 => "base64",
204            KeyEncoding::Hex => "hex",
205        }
206    }
207}
208
209fn base64_symbol(byte: u8) -> Option<u8> {
210    match byte {
211        b'A'..=b'Z' => Some(byte - b'A'),
212        b'a'..=b'z' => Some(byte - b'a' + 26),
213        b'0'..=b'9' => Some(byte - b'0' + 52),
214        // NOTE: accepts the URL-safe alphabet too — Node emits it for `base64url` encodings.
215        b'+' | b'-' => Some(62),
216        b'/' | b'_' => Some(63),
217        _ => None,
218    }
219}
220
221/// Standard and URL-safe base64, padding optional. `None` on any symbol outside the alphabet or a
222/// length that cannot be a whole number of bytes.
223pub fn decode_base64(raw: &str) -> Option<Vec<u8>> {
224    let symbols: &[u8] = raw.trim_end_matches('=').as_bytes();
225    if symbols.len() % 4 == 1 {
226        return None;
227    }
228    let mut out = Vec::with_capacity(symbols.len() * 3 / 4);
229    let mut accumulator: u32 = 0;
230    let mut bits = 0u32;
231    for byte in symbols {
232        accumulator = (accumulator << 6) | u32::from(base64_symbol(*byte)?);
233        bits += 6;
234        if bits >= 8 {
235            bits -= 8;
236            out.push((accumulator >> bits) as u8);
237        }
238    }
239    // Leftover bits of a truncated group must be zero, or the input was not base64 of these bytes.
240    if accumulator & ((1 << bits) - 1) != 0 {
241        return None;
242    }
243    Some(out)
244}
245
246/// Lowercase or uppercase hex, no separators. `None` on an odd length or a non-hex digit.
247pub fn decode_hex(raw: &str) -> Option<Vec<u8>> {
248    let digits = raw.as_bytes();
249    if !digits.len().is_multiple_of(2) {
250        return None;
251    }
252    let mut out = Vec::with_capacity(digits.len() / 2);
253    for pair in digits.chunks_exact(2) {
254        let high = (pair[0] as char).to_digit(16)?;
255        let low = (pair[1] as char).to_digit(16)?;
256        out.push((high * 16 + low) as u8);
257    }
258    Some(out)
259}
260
261/// The `cypher` sub-document of the `open()` options document, on its own — `{ keys, keyId,
262/// keyEncoding, onMissingKey }`. Public because a host that reads key material from a file or an
263/// environment variable (`crate::keys`) has such a document and no options document around it.
264pub fn parse_cypher(value: &Value) -> Result<CipherOptions, OptionsError> {
265    let object = as_object(value, "cypher")?;
266    let encoding = match optional_string(object, "keyEncoding")?.as_deref() {
267        None | Some("base64") => KeyEncoding::Base64,
268        Some("hex") => KeyEncoding::Hex,
269        Some(other) => {
270            return shape(format!(
271                "\"keyEncoding\" must be \"base64\" or \"hex\" — got \"{other}\""
272            ))
273        }
274    };
275
276    let raw_keys = match object.get("keys") {
277        Some(keys) => as_object(keys, "cypher.keys")?,
278        None => return shape("\"cypher\" needs a \"keys\" object"),
279    };
280
281    let mut keys = HashMap::with_capacity(raw_keys.len());
282    for (id, material) in raw_keys {
283        let Some(material) = material.as_str() else {
284            return shape(format!("key \"{id}\" must be a string"));
285        };
286        keys.insert(id.clone(), decode_key(id, material, encoding)?);
287    }
288
289    let on_missing_key = match optional_string(object, "onMissingKey")? {
290        Some(raw) => Some(parse_missing_key_policy(&raw)?),
291        None => None,
292    };
293
294    Ok(CipherOptions {
295        keys,
296        key_id: optional_string(object, "keyId")?,
297        on_missing_key,
298    })
299}
300
301/// Builds `OpenOptions` from the JSON document `open()` takes. Every member is optional; an absent
302/// one keeps the engine's own default, so `{}` and `null` both mean "open it the usual way".
303pub fn parse_open_options(value: &Value) -> Result<OpenOptions, OptionsError> {
304    let mut options = OpenOptions::default();
305    if value.is_null() {
306        return Ok(options);
307    }
308    let object = as_object(value, "options")?;
309
310    if let Some(readonly) = optional_bool(object, "readonly")? {
311        options.readonly = readonly;
312    }
313    if let Some(snapshot_every) = optional_u64(object, "snapshotEvery")? {
314        options.snapshot_every = snapshot_every;
315    }
316    if let Some(compaction) = object.get("compaction").filter(|value| !value.is_null()) {
317        options.compaction = Some(parse_compaction(compaction)?);
318    }
319    if let Some(lock) = object.get("lock").filter(|value| !value.is_null()) {
320        options.lock = parse_lock(lock)?;
321    }
322    if let Some(cypher) = object.get("cypher").filter(|value| !value.is_null()) {
323        options.cypher = Some(parse_cypher(cypher)?);
324    }
325    if let Some(follow) = object.get("follow").filter(|value| !value.is_null()) {
326        options.follow = parse_follow(follow)?;
327    }
328    options.layout = parse_layout(object)?;
329
330    Ok(options)
331}
332
333/// Builds [`LayoutMigrationOptions`] from the JSON document `migrateLayout()` takes — the TS
334/// `LayoutMigrationOptions`, member for member, plus the `lock` of `open()` so a host that has to
335/// wait differently for the writer lock can say so. Every member is optional; `{}` and `null` both
336/// mean "move it into the nested arrangement, keeping the document's name".
337///
338/// Neither pair of document names is resolved here, for the same reason `parse_layout` resolves
339/// nothing: whether the two names of a pair agree is the engine's refusal to make, so it reads the
340/// same however a caller reaches it.
341pub fn parse_migrate_layout_options(value: &Value) -> Result<LayoutMigrationOptions, OptionsError> {
342    let mut options = LayoutMigrationOptions::default();
343    if value.is_null() {
344        return Ok(options);
345    }
346    let object = as_object(value, "options")?;
347
348    options.to = match optional_string(object, "to")? {
349        Some(raw) => Some(parse_migration_target(&raw)?),
350        None => None,
351    };
352    options.from_metadata_file = optional_string(object, "fromMetadataFile")?;
353    options.from_manifest = optional_string(object, "fromManifest")?;
354    options.metadata_file = optional_string(object, "metadataFile")?;
355    options.manifest_file = optional_string(object, "manifestFile")?;
356    options.dry_run = optional_bool(object, "dryRun")?.unwrap_or(false);
357    if let Some(lock) = object.get("lock").filter(|value| !value.is_null()) {
358        options.lock = parse_lock(lock)?;
359    }
360
361    Ok(options)
362}
363
364/// Builds [`VerifyOptions`] from the JSON document `verify()` takes:
365/// `{ relations?: boolean, images?: boolean, maxImageBytes?: number }`.
366/// `null` and `{}` mean the defaults.
367pub fn parse_verify_options(value: &Value) -> Result<VerifyOptions, OptionsError> {
368    let mut options = VerifyOptions::default();
369    if value.is_null() {
370        return Ok(options);
371    }
372    let object = as_object(value, "options")?;
373    if let Some(relations) = optional_bool(object, "relations")? {
374        options.relations = relations;
375    }
376    if let Some(images) = optional_bool(object, "images")? {
377        options.images = images;
378    }
379    options.max_image_bytes = match object.get("maxImageBytes") {
380        None | Some(Value::Null) => None,
381        Some(value) => match value.as_u64() {
382            Some(bytes) => Some(bytes),
383            None => return shape("\"maxImageBytes\" must be a non-negative integer".to_string()),
384        },
385    };
386    Ok(options)
387}
388
389/// Builds [`BackupOptions`] from the JSON document `backup()` takes: `{ indexes?: boolean, lock? }`.
390pub fn parse_backup_options(value: &Value) -> Result<BackupOptions, OptionsError> {
391    let mut options = BackupOptions::default();
392    if value.is_null() {
393        return Ok(options);
394    }
395    let object = as_object(value, "options")?;
396    options.indexes = optional_bool(object, "indexes")?.unwrap_or(false);
397    if let Some(lock) = object.get("lock").filter(|value| !value.is_null()) {
398        options.lock = parse_lock(lock)?;
399    }
400    Ok(options)
401}
402
403/// Builds [`RestoreOptions`] from the JSON document `restore()` takes: `{ lock? }`.
404pub fn parse_restore_options(value: &Value) -> Result<RestoreOptions, OptionsError> {
405    let mut options = RestoreOptions::default();
406    if value.is_null() {
407        return Ok(options);
408    }
409    let object = as_object(value, "options")?;
410    if let Some(lock) = object.get("lock").filter(|value| !value.is_null()) {
411        options.lock = parse_lock(lock)?;
412    }
413    Ok(options)
414}
415
416fn parse_migration_target(raw: &str) -> Result<LayoutKind, OptionsError> {
417    match raw {
418        "flat" => Ok(LayoutKind::Flat),
419        "nested" => Ok(LayoutKind::Nested),
420        other => shape(format!("\"to\" must be \"flat\" or \"nested\" — got \"{other}\"")),
421    }
422}
423
424#[cfg(test)]
425mod tests {
426    use serde_json::json;
427
428    use super::*;
429
430    #[test]
431    fn an_absent_document_keeps_every_engine_default() {
432        let options = parse_open_options(&Value::Null).unwrap();
433
434        assert!(!options.readonly);
435        assert_eq!(options.snapshot_every, OpenOptions::default().snapshot_every);
436        assert!(options.cypher.is_none());
437    }
438
439    #[test]
440    fn readonly_snapshot_every_and_lock_reach_the_engine_options() {
441        let options = parse_open_options(&json!({
442            "readonly": true,
443            "snapshotEvery": 5,
444            "lock": { "timeoutMs": 0, "retryIntervalMs": 10 },
445        }))
446        .unwrap();
447
448        assert!(options.readonly);
449        assert_eq!(options.snapshot_every, 5);
450        let lock = options
451            .lock
452            .options()
453            .expect("an object shape asks for a lock, not for skipping");
454        assert_eq!(lock.timeout_ms, Some(0));
455        assert_eq!(lock.retry_interval_ms, Some(10));
456        assert_eq!(lock.heartbeat_ms, None);
457    }
458
459    #[test]
460    fn compaction_reaches_the_engine_in_both_the_thresholds_and_the_false_shape() {
461        let named = parse_open_options(&json!({
462            "compaction": { "deadBytesRatio": 0.5, "minDeadBytes": 200 },
463        }))
464        .unwrap();
465        assert_eq!(
466            named.compaction,
467            Some(CatalogCompaction::Enabled {
468                dead_bytes_ratio: 0.5,
469                min_dead_bytes: 200
470            })
471        );
472
473        let off = parse_open_options(&json!({ "compaction": false })).unwrap();
474        assert_eq!(off.compaction, Some(CatalogCompaction::Disabled));
475
476        // NOTE: absent and null both mean "leave it to the catalog", which is not the same as false.
477        for document in [json!({}), json!({ "compaction": null })] {
478            assert_eq!(parse_open_options(&document).unwrap().compaction, None, "{document}");
479        }
480    }
481
482    #[test]
483    fn a_compaction_ratio_outside_zero_to_one_is_refused_before_the_engine_is_touched() {
484        for ratio in [json!(0), json!(1.5), json!("half")] {
485            let document = json!({ "compaction": { "deadBytesRatio": ratio, "minDeadBytes": 1 } });
486            assert!(parse_open_options(&document).is_err(), "{document}");
487        }
488        assert!(parse_open_options(&json!({ "compaction": true })).is_err());
489    }
490
491    #[test]
492    fn lock_false_asks_the_engine_to_skip_the_writer_lock_and_true_asks_for_the_defaults() {
493        assert!(matches!(
494            parse_open_options(&json!({ "lock": false })).unwrap().lock,
495            LockMode::Skip
496        ));
497
498        // NOTE: absent and null must stay the locked default — skipping is opt-in only.
499        for document in [
500            json!({}),
501            json!({ "lock": null }),
502            json!({ "lock": true }),
503            json!({ "lock": {} }),
504        ] {
505            let lock = parse_open_options(&document).unwrap().lock;
506            assert!(matches!(lock, LockMode::Enabled(_)), "{document} must keep the lock");
507            assert_eq!(lock.options().unwrap().timeout_ms, None);
508        }
509    }
510
511    #[test]
512    fn a_lock_that_is_neither_a_flag_nor_an_options_object_is_refused_as_a_shape_error() {
513        assert_eq!(
514            parse_open_options(&json!({ "lock": "off" })).unwrap_err(),
515            OptionsError::Shape("\"lock\" must be a boolean or an object of lock options".to_string())
516        );
517        assert_eq!(
518            parse_open_options(&json!({ "lock": { "timeoutMs": -1 } })).unwrap_err(),
519            OptionsError::Shape("\"timeoutMs\" must be a non-negative whole number".to_string())
520        );
521    }
522
523    #[test]
524    fn a_base64_keyring_decodes_to_the_exact_bytes_and_keeps_its_write_key() {
525        let options = parse_open_options(&json!({
526            "cypher": {
527                "keys": { "k1": "AAECAw==" },
528                "keyId": "k1",
529                "onMissingKey": "omit",
530            },
531        }))
532        .unwrap();
533
534        let cypher = options.cypher.unwrap();
535        assert_eq!(cypher.keys["k1"], vec![0, 1, 2, 3]);
536        assert_eq!(cypher.key_id.as_deref(), Some("k1"));
537        assert_eq!(cypher.on_missing_key, Some(MissingKeyPolicy::Omit));
538    }
539
540    #[test]
541    fn a_hex_keyring_decodes_only_when_key_encoding_says_so() {
542        let hex = json!({ "cypher": { "keys": { "k1": "00010203" }, "keyEncoding": "hex" } });
543        let options = parse_open_options(&hex).unwrap();
544        assert_eq!(options.cypher.unwrap().keys["k1"], vec![0, 1, 2, 3]);
545
546        // NOTE: "00010203" is also valid base64 — the same text decodes to different bytes.
547        let as_base64 = json!({ "cypher": { "keys": { "k1": "00010203" } } });
548        assert_ne!(
549            parse_open_options(&as_base64).unwrap().cypher.unwrap().keys["k1"],
550            vec![0, 1, 2, 3]
551        );
552    }
553
554    #[test]
555    fn unusable_key_material_is_reported_as_a_key_error_naming_the_key() {
556        let error = parse_open_options(&json!({ "cypher": { "keys": { "k1": "!!!!" } } })).unwrap_err();
557
558        assert_eq!(error, OptionsError::Key("key \"k1\" is not valid base64".to_string()));
559    }
560
561    #[test]
562    fn a_wrong_typed_option_is_refused_as_a_shape_error_naming_the_member() {
563        assert_eq!(
564            parse_open_options(&json!({ "readonly": "yes" })).unwrap_err(),
565            OptionsError::Shape("\"readonly\" must be a boolean".to_string())
566        );
567        assert_eq!(
568            parse_open_options(&json!({ "snapshotEvery": -1 })).unwrap_err(),
569            OptionsError::Shape("\"snapshotEvery\" must be a non-negative whole number".to_string())
570        );
571        assert!(matches!(
572            parse_open_options(&json!({ "cypher": { "keys": {}, "onMissingKey": "shrug" } })).unwrap_err(),
573            OptionsError::Shape(_)
574        ));
575    }
576
577    #[test]
578    fn follow_reaches_the_engine_in_all_three_shapes_the_option_takes() {
579        assert_eq!(parse_open_options(&json!({})).unwrap().follow, FollowOption::Default);
580        assert_eq!(
581            parse_open_options(&json!({ "follow": null })).unwrap().follow,
582            FollowOption::Default
583        );
584        assert_eq!(
585            parse_open_options(&json!({ "follow": false })).unwrap().follow,
586            FollowOption::Off
587        );
588        assert_eq!(
589            parse_open_options(&json!({ "follow": true })).unwrap().follow,
590            FollowOption::Every(Duration::ZERO)
591        );
592        assert_eq!(
593            parse_open_options(&json!({ "follow": { "intervalMs": 250 } }))
594                .unwrap()
595                .follow,
596            FollowOption::Every(Duration::from_millis(250))
597        );
598        assert_eq!(
599            parse_open_options(&json!({ "follow": {} })).unwrap().follow,
600            FollowOption::Every(Duration::ZERO)
601        );
602    }
603
604    #[test]
605    fn a_follow_that_is_neither_a_flag_nor_an_interval_is_refused_as_a_shape_error() {
606        assert!(matches!(
607            parse_open_options(&json!({ "follow": "always" })).unwrap_err(),
608            OptionsError::Shape(_)
609        ));
610        assert!(matches!(
611            parse_open_options(&json!({ "follow": { "intervalMs": -1 } })).unwrap_err(),
612            OptionsError::Shape(_)
613        ));
614    }
615
616    #[test]
617    fn the_layout_triple_reaches_the_engine_unresolved() {
618        assert_eq!(parse_open_options(&json!({})).unwrap().layout, LayoutOptions::default());
619
620        let named = parse_open_options(&json!({
621            "layout": "nested",
622            "metadataFile": "cerebro.json",
623        }))
624        .unwrap();
625        assert_eq!(named.layout.kind, Some(LayoutKind::Nested));
626        assert_eq!(named.layout.metadata_file.as_deref(), Some("cerebro.json"));
627        assert_eq!(named.layout.manifest, None);
628
629        // NOTE: the two names are passed on as given — the engine, not this, decides they conflict.
630        let both = parse_open_options(&json!({ "manifest": "a.json", "metadataFile": "b.json" })).unwrap();
631        assert_eq!(both.layout.manifest.as_deref(), Some("a.json"));
632        assert_eq!(both.layout.metadata_file.as_deref(), Some("b.json"));
633    }
634
635    #[test]
636    fn an_unknown_layout_kind_and_a_non_string_file_name_are_refused_as_shape_errors() {
637        assert_eq!(
638            parse_open_options(&json!({ "layout": "sideways" })).unwrap_err(),
639            OptionsError::Shape("\"layout\" must be \"flat\" or \"nested\" — got \"sideways\"".to_string())
640        );
641        assert_eq!(
642            parse_open_options(&json!({ "metadataFile": 7 })).unwrap_err(),
643            OptionsError::Shape("\"metadataFile\" must be a string".to_string())
644        );
645    }
646
647    #[test]
648    fn a_migration_with_no_document_moves_into_the_nested_arrangement_under_the_engine_lock() {
649        let options = parse_migrate_layout_options(&Value::Null).unwrap();
650
651        assert_eq!(options.to, None, "absent is the engine's own default, not a second one");
652        assert!(!options.dry_run);
653        assert!(options.metadata_file.is_none() && options.from_metadata_file.is_none());
654        assert!(matches!(options.lock, LockMode::Enabled(_)));
655    }
656
657    #[test]
658    fn both_document_name_pairs_reach_the_engine_unresolved_so_it_makes_the_refusal() {
659        let options = parse_migrate_layout_options(&json!({
660            "to": "flat",
661            "fromMetadataFile": "cerebro.json",
662            "fromManifest": "legacy.json",
663            "metadataFile": "hayson.json",
664            "manifestFile": "old.json",
665            "dryRun": true,
666        }))
667        .unwrap();
668
669        assert_eq!(options.to, Some(LayoutKind::Flat));
670        assert_eq!(options.from_metadata_file.as_deref(), Some("cerebro.json"));
671        assert_eq!(options.from_manifest.as_deref(), Some("legacy.json"));
672        assert_eq!(options.metadata_file.as_deref(), Some("hayson.json"));
673        assert_eq!(options.manifest_file.as_deref(), Some("old.json"));
674        assert!(options.dry_run);
675    }
676
677    #[test]
678    fn a_migration_takes_the_same_lock_document_an_open_takes() {
679        let options = parse_migrate_layout_options(&json!({ "lock": { "timeoutMs": 0 } })).unwrap();
680
681        assert_eq!(
682            options.lock.options().and_then(|lock| lock.timeout_ms),
683            Some(0),
684            "a host that owns the wait has to be able to ask for a fail-fast attempt"
685        );
686        let skipped = parse_migrate_layout_options(&json!({ "lock": false })).unwrap();
687        assert!(matches!(skipped.lock, LockMode::Skip));
688    }
689
690    #[test]
691    fn an_unknown_migration_target_is_refused_as_a_shape_error() {
692        assert_eq!(
693            parse_migrate_layout_options(&json!({ "to": "sideways" })).unwrap_err(),
694            OptionsError::Shape("\"to\" must be \"flat\" or \"nested\" — got \"sideways\"".to_string())
695        );
696        assert_eq!(
697            parse_migrate_layout_options(&json!({ "dryRun": "yes" })).unwrap_err(),
698            OptionsError::Shape("\"dryRun\" must be a boolean".to_string())
699        );
700    }
701
702    #[test]
703    fn base64_accepts_the_url_safe_alphabet_and_optional_padding() {
704        assert_eq!(decode_base64("+/8="), decode_base64("-_8"));
705        assert_eq!(decode_base64(""), Some(Vec::new()));
706        assert_eq!(decode_base64("QQ"), Some(vec![b'A']));
707        assert_eq!(decode_base64("QQ=="), Some(vec![b'A']));
708    }
709
710    #[test]
711    fn base64_refuses_a_length_and_a_symbol_that_cannot_be_base64() {
712        assert_eq!(decode_base64("A"), None);
713        assert_eq!(decode_base64("QQ*="), None);
714    }
715
716    #[test]
717    fn hex_round_trips_both_cases_and_refuses_odd_or_non_hex_input() {
718        assert_eq!(decode_hex("DEADbeef"), Some(vec![0xde, 0xad, 0xbe, 0xef]));
719        assert_eq!(decode_hex("abc"), None);
720        assert_eq!(decode_hex("zz"), None);
721    }
722}