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, PackLimits,
9    PackOptions, RestoreOptions, UnpackOptions, 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_pack_limits(object: &serde_json::Map<String, Value>) -> Result<PackLimits, OptionsError> {
417    let mut limits = PackLimits::default();
418    let Some(raw) = object.get("limits").filter(|value| !value.is_null()) else {
419        return Ok(limits);
420    };
421    let raw = as_object(raw, "limits")?;
422    let number = |key: &str| -> Result<Option<u64>, OptionsError> {
423        match raw.get(key).filter(|value| !value.is_null()) {
424            None => Ok(None),
425            Some(value) => match value.as_u64() {
426                Some(number) => Ok(Some(number)),
427                None => shape(format!("\"limits.{key}\" must be a non-negative integer")),
428            },
429        }
430    };
431    if let Some(value) = number("maxArchiveBytes")? {
432        limits.max_archive_bytes = value;
433    }
434    if let Some(value) = number("maxTotalBytes")? {
435        limits.max_total_bytes = value;
436    }
437    if let Some(value) = number("maxEntryBytes")? {
438        limits.max_entry_bytes = value;
439    }
440    if let Some(value) = number("maxEntries")? {
441        limits.max_entries = value as usize;
442    }
443    Ok(limits)
444}
445
446/// Builds [`PackLimits`] from `{ limits?: { maxArchiveBytes?, maxTotalBytes?, maxEntryBytes?, maxEntries? } }`.
447pub fn parse_pack_limits_options(value: &Value) -> Result<PackLimits, OptionsError> {
448    if value.is_null() {
449        return Ok(PackLimits::default());
450    }
451    parse_pack_limits(as_object(value, "options")?)
452}
453
454/// Builds [`PackOptions`] from the JSON document `pack()` takes:
455/// `{ indexes?: boolean, extra?: { [entryName]: string }, limits?, lock? }`.
456pub fn parse_pack_options(value: &Value) -> Result<PackOptions, OptionsError> {
457    let mut options = PackOptions::default();
458    if value.is_null() {
459        return Ok(options);
460    }
461    let object = as_object(value, "options")?;
462    options.indexes = optional_bool(object, "indexes")?.unwrap_or(false);
463    if let Some(extra) = object.get("extra").filter(|value| !value.is_null()) {
464        for (name, content) in as_object(extra, "extra")? {
465            match content.as_str() {
466                Some(text) => options.extra.push((name.clone(), text.as_bytes().to_vec())),
467                None => return shape(format!("\"extra.{name}\" must be a string")),
468            }
469        }
470    }
471    options.limits = parse_pack_limits(object)?;
472    if let Some(lock) = object.get("lock").filter(|value| !value.is_null()) {
473        options.lock = parse_lock(lock)?;
474    }
475    Ok(options)
476}
477
478/// Builds [`UnpackOptions`] from the JSON document `unpack()` takes: `{ limits?, lock? }`.
479pub fn parse_unpack_options(value: &Value) -> Result<UnpackOptions, OptionsError> {
480    let mut options = UnpackOptions::default();
481    if value.is_null() {
482        return Ok(options);
483    }
484    let object = as_object(value, "options")?;
485    options.limits = parse_pack_limits(object)?;
486    if let Some(lock) = object.get("lock").filter(|value| !value.is_null()) {
487        options.lock = parse_lock(lock)?;
488    }
489    Ok(options)
490}
491
492fn parse_migration_target(raw: &str) -> Result<LayoutKind, OptionsError> {
493    match raw {
494        "flat" => Ok(LayoutKind::Flat),
495        "nested" => Ok(LayoutKind::Nested),
496        other => shape(format!("\"to\" must be \"flat\" or \"nested\" — got \"{other}\"")),
497    }
498}
499
500#[cfg(test)]
501mod tests {
502    use serde_json::json;
503
504    use super::*;
505
506    #[test]
507    fn an_absent_document_keeps_every_engine_default() {
508        let options = parse_open_options(&Value::Null).unwrap();
509
510        assert!(!options.readonly);
511        assert_eq!(options.snapshot_every, OpenOptions::default().snapshot_every);
512        assert!(options.cypher.is_none());
513    }
514
515    #[test]
516    fn readonly_snapshot_every_and_lock_reach_the_engine_options() {
517        let options = parse_open_options(&json!({
518            "readonly": true,
519            "snapshotEvery": 5,
520            "lock": { "timeoutMs": 0, "retryIntervalMs": 10 },
521        }))
522        .unwrap();
523
524        assert!(options.readonly);
525        assert_eq!(options.snapshot_every, 5);
526        let lock = options
527            .lock
528            .options()
529            .expect("an object shape asks for a lock, not for skipping");
530        assert_eq!(lock.timeout_ms, Some(0));
531        assert_eq!(lock.retry_interval_ms, Some(10));
532        assert_eq!(lock.heartbeat_ms, None);
533    }
534
535    #[test]
536    fn compaction_reaches_the_engine_in_both_the_thresholds_and_the_false_shape() {
537        let named = parse_open_options(&json!({
538            "compaction": { "deadBytesRatio": 0.5, "minDeadBytes": 200 },
539        }))
540        .unwrap();
541        assert_eq!(
542            named.compaction,
543            Some(CatalogCompaction::Enabled {
544                dead_bytes_ratio: 0.5,
545                min_dead_bytes: 200
546            })
547        );
548
549        let off = parse_open_options(&json!({ "compaction": false })).unwrap();
550        assert_eq!(off.compaction, Some(CatalogCompaction::Disabled));
551
552        // NOTE: absent and null both mean "leave it to the catalog", which is not the same as false.
553        for document in [json!({}), json!({ "compaction": null })] {
554            assert_eq!(parse_open_options(&document).unwrap().compaction, None, "{document}");
555        }
556    }
557
558    #[test]
559    fn a_compaction_ratio_outside_zero_to_one_is_refused_before_the_engine_is_touched() {
560        for ratio in [json!(0), json!(1.5), json!("half")] {
561            let document = json!({ "compaction": { "deadBytesRatio": ratio, "minDeadBytes": 1 } });
562            assert!(parse_open_options(&document).is_err(), "{document}");
563        }
564        assert!(parse_open_options(&json!({ "compaction": true })).is_err());
565    }
566
567    #[test]
568    fn lock_false_asks_the_engine_to_skip_the_writer_lock_and_true_asks_for_the_defaults() {
569        assert!(matches!(
570            parse_open_options(&json!({ "lock": false })).unwrap().lock,
571            LockMode::Skip
572        ));
573
574        // NOTE: absent and null must stay the locked default — skipping is opt-in only.
575        for document in [
576            json!({}),
577            json!({ "lock": null }),
578            json!({ "lock": true }),
579            json!({ "lock": {} }),
580        ] {
581            let lock = parse_open_options(&document).unwrap().lock;
582            assert!(matches!(lock, LockMode::Enabled(_)), "{document} must keep the lock");
583            assert_eq!(lock.options().unwrap().timeout_ms, None);
584        }
585    }
586
587    #[test]
588    fn a_lock_that_is_neither_a_flag_nor_an_options_object_is_refused_as_a_shape_error() {
589        assert_eq!(
590            parse_open_options(&json!({ "lock": "off" })).unwrap_err(),
591            OptionsError::Shape("\"lock\" must be a boolean or an object of lock options".to_string())
592        );
593        assert_eq!(
594            parse_open_options(&json!({ "lock": { "timeoutMs": -1 } })).unwrap_err(),
595            OptionsError::Shape("\"timeoutMs\" must be a non-negative whole number".to_string())
596        );
597    }
598
599    #[test]
600    fn a_base64_keyring_decodes_to_the_exact_bytes_and_keeps_its_write_key() {
601        let options = parse_open_options(&json!({
602            "cypher": {
603                "keys": { "k1": "AAECAw==" },
604                "keyId": "k1",
605                "onMissingKey": "omit",
606            },
607        }))
608        .unwrap();
609
610        let cypher = options.cypher.unwrap();
611        assert_eq!(cypher.keys["k1"], vec![0, 1, 2, 3]);
612        assert_eq!(cypher.key_id.as_deref(), Some("k1"));
613        assert_eq!(cypher.on_missing_key, Some(MissingKeyPolicy::Omit));
614    }
615
616    #[test]
617    fn a_hex_keyring_decodes_only_when_key_encoding_says_so() {
618        let hex = json!({ "cypher": { "keys": { "k1": "00010203" }, "keyEncoding": "hex" } });
619        let options = parse_open_options(&hex).unwrap();
620        assert_eq!(options.cypher.unwrap().keys["k1"], vec![0, 1, 2, 3]);
621
622        // NOTE: "00010203" is also valid base64 — the same text decodes to different bytes.
623        let as_base64 = json!({ "cypher": { "keys": { "k1": "00010203" } } });
624        assert_ne!(
625            parse_open_options(&as_base64).unwrap().cypher.unwrap().keys["k1"],
626            vec![0, 1, 2, 3]
627        );
628    }
629
630    #[test]
631    fn unusable_key_material_is_reported_as_a_key_error_naming_the_key() {
632        let error = parse_open_options(&json!({ "cypher": { "keys": { "k1": "!!!!" } } })).unwrap_err();
633
634        assert_eq!(error, OptionsError::Key("key \"k1\" is not valid base64".to_string()));
635    }
636
637    #[test]
638    fn a_wrong_typed_option_is_refused_as_a_shape_error_naming_the_member() {
639        assert_eq!(
640            parse_open_options(&json!({ "readonly": "yes" })).unwrap_err(),
641            OptionsError::Shape("\"readonly\" must be a boolean".to_string())
642        );
643        assert_eq!(
644            parse_open_options(&json!({ "snapshotEvery": -1 })).unwrap_err(),
645            OptionsError::Shape("\"snapshotEvery\" must be a non-negative whole number".to_string())
646        );
647        assert!(matches!(
648            parse_open_options(&json!({ "cypher": { "keys": {}, "onMissingKey": "shrug" } })).unwrap_err(),
649            OptionsError::Shape(_)
650        ));
651    }
652
653    #[test]
654    fn follow_reaches_the_engine_in_all_three_shapes_the_option_takes() {
655        assert_eq!(parse_open_options(&json!({})).unwrap().follow, FollowOption::Default);
656        assert_eq!(
657            parse_open_options(&json!({ "follow": null })).unwrap().follow,
658            FollowOption::Default
659        );
660        assert_eq!(
661            parse_open_options(&json!({ "follow": false })).unwrap().follow,
662            FollowOption::Off
663        );
664        assert_eq!(
665            parse_open_options(&json!({ "follow": true })).unwrap().follow,
666            FollowOption::Every(Duration::ZERO)
667        );
668        assert_eq!(
669            parse_open_options(&json!({ "follow": { "intervalMs": 250 } }))
670                .unwrap()
671                .follow,
672            FollowOption::Every(Duration::from_millis(250))
673        );
674        assert_eq!(
675            parse_open_options(&json!({ "follow": {} })).unwrap().follow,
676            FollowOption::Every(Duration::ZERO)
677        );
678    }
679
680    #[test]
681    fn a_follow_that_is_neither_a_flag_nor_an_interval_is_refused_as_a_shape_error() {
682        assert!(matches!(
683            parse_open_options(&json!({ "follow": "always" })).unwrap_err(),
684            OptionsError::Shape(_)
685        ));
686        assert!(matches!(
687            parse_open_options(&json!({ "follow": { "intervalMs": -1 } })).unwrap_err(),
688            OptionsError::Shape(_)
689        ));
690    }
691
692    #[test]
693    fn the_layout_triple_reaches_the_engine_unresolved() {
694        assert_eq!(parse_open_options(&json!({})).unwrap().layout, LayoutOptions::default());
695
696        let named = parse_open_options(&json!({
697            "layout": "nested",
698            "metadataFile": "cerebro.json",
699        }))
700        .unwrap();
701        assert_eq!(named.layout.kind, Some(LayoutKind::Nested));
702        assert_eq!(named.layout.metadata_file.as_deref(), Some("cerebro.json"));
703        assert_eq!(named.layout.manifest, None);
704
705        // NOTE: the two names are passed on as given — the engine, not this, decides they conflict.
706        let both = parse_open_options(&json!({ "manifest": "a.json", "metadataFile": "b.json" })).unwrap();
707        assert_eq!(both.layout.manifest.as_deref(), Some("a.json"));
708        assert_eq!(both.layout.metadata_file.as_deref(), Some("b.json"));
709    }
710
711    #[test]
712    fn an_unknown_layout_kind_and_a_non_string_file_name_are_refused_as_shape_errors() {
713        assert_eq!(
714            parse_open_options(&json!({ "layout": "sideways" })).unwrap_err(),
715            OptionsError::Shape("\"layout\" must be \"flat\" or \"nested\" — got \"sideways\"".to_string())
716        );
717        assert_eq!(
718            parse_open_options(&json!({ "metadataFile": 7 })).unwrap_err(),
719            OptionsError::Shape("\"metadataFile\" must be a string".to_string())
720        );
721    }
722
723    #[test]
724    fn a_migration_with_no_document_moves_into_the_nested_arrangement_under_the_engine_lock() {
725        let options = parse_migrate_layout_options(&Value::Null).unwrap();
726
727        assert_eq!(options.to, None, "absent is the engine's own default, not a second one");
728        assert!(!options.dry_run);
729        assert!(options.metadata_file.is_none() && options.from_metadata_file.is_none());
730        assert!(matches!(options.lock, LockMode::Enabled(_)));
731    }
732
733    #[test]
734    fn both_document_name_pairs_reach_the_engine_unresolved_so_it_makes_the_refusal() {
735        let options = parse_migrate_layout_options(&json!({
736            "to": "flat",
737            "fromMetadataFile": "cerebro.json",
738            "fromManifest": "legacy.json",
739            "metadataFile": "hayson.json",
740            "manifestFile": "old.json",
741            "dryRun": true,
742        }))
743        .unwrap();
744
745        assert_eq!(options.to, Some(LayoutKind::Flat));
746        assert_eq!(options.from_metadata_file.as_deref(), Some("cerebro.json"));
747        assert_eq!(options.from_manifest.as_deref(), Some("legacy.json"));
748        assert_eq!(options.metadata_file.as_deref(), Some("hayson.json"));
749        assert_eq!(options.manifest_file.as_deref(), Some("old.json"));
750        assert!(options.dry_run);
751    }
752
753    #[test]
754    fn a_migration_takes_the_same_lock_document_an_open_takes() {
755        let options = parse_migrate_layout_options(&json!({ "lock": { "timeoutMs": 0 } })).unwrap();
756
757        assert_eq!(
758            options.lock.options().and_then(|lock| lock.timeout_ms),
759            Some(0),
760            "a host that owns the wait has to be able to ask for a fail-fast attempt"
761        );
762        let skipped = parse_migrate_layout_options(&json!({ "lock": false })).unwrap();
763        assert!(matches!(skipped.lock, LockMode::Skip));
764    }
765
766    #[test]
767    fn an_unknown_migration_target_is_refused_as_a_shape_error() {
768        assert_eq!(
769            parse_migrate_layout_options(&json!({ "to": "sideways" })).unwrap_err(),
770            OptionsError::Shape("\"to\" must be \"flat\" or \"nested\" — got \"sideways\"".to_string())
771        );
772        assert_eq!(
773            parse_migrate_layout_options(&json!({ "dryRun": "yes" })).unwrap_err(),
774            OptionsError::Shape("\"dryRun\" must be a boolean".to_string())
775        );
776    }
777
778    #[test]
779    fn base64_accepts_the_url_safe_alphabet_and_optional_padding() {
780        assert_eq!(decode_base64("+/8="), decode_base64("-_8"));
781        assert_eq!(decode_base64(""), Some(Vec::new()));
782        assert_eq!(decode_base64("QQ"), Some(vec![b'A']));
783        assert_eq!(decode_base64("QQ=="), Some(vec![b'A']));
784    }
785
786    #[test]
787    fn base64_refuses_a_length_and_a_symbol_that_cannot_be_base64() {
788        assert_eq!(decode_base64("A"), None);
789        assert_eq!(decode_base64("QQ*="), None);
790    }
791
792    #[test]
793    fn hex_round_trips_both_cases_and_refuses_odd_or_non_hex_input() {
794        assert_eq!(decode_hex("DEADbeef"), Some(vec![0xde, 0xad, 0xbe, 0xef]));
795        assert_eq!(decode_hex("abc"), None);
796        assert_eq!(decode_hex("zz"), None);
797    }
798
799    #[test]
800    fn pack_options_carry_extra_entries_limits_and_the_lock() {
801        let options = parse_pack_options(&json!({
802            "indexes": true,
803            "extra": { "gly.json": "{}" },
804            "limits": { "maxEntries": 5, "maxEntryBytes": 10 },
805        }))
806        .unwrap();
807
808        assert!(options.indexes);
809        assert_eq!(options.extra, vec![("gly.json".to_string(), b"{}".to_vec())]);
810        assert_eq!(options.limits.max_entries, 5);
811        assert_eq!(options.limits.max_entry_bytes, 10);
812        assert_eq!(
813            options.limits.max_archive_bytes,
814            PackLimits::default().max_archive_bytes
815        );
816        assert!(parse_pack_options(&json!({ "extra": { "a": 1 } })).is_err());
817        assert!(parse_unpack_options(&json!({ "limits": { "maxEntries": -1 } })).is_err());
818        assert_eq!(
819            parse_unpack_options(&Value::Null).unwrap().limits,
820            PackLimits::default()
821        );
822    }
823}