hayson-binding-shared 0.6.0

Shared error mapping, JSON shapes, options and predicate parsing for hayson's NAPI and WASM language bindings
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
use hayson_engine::catalog::{IntegrityReport, MigrateOutcome, OrphanRecord, Relation};
use hayson_engine::compaction::CompactionResult;
use hayson_engine::database::{Layout, LayoutMigrationResult};
use hayson_engine::query::{AccessPathSummary, OverlayStrategy, PlanBranch, PlanOverlay, QueryStrategy};
use hayson_engine::schema::HaysonRecord;
use hayson_engine::table::{BrokenLink, RefreshOutcome, RotationResult, TableStats};
use hayson_engine::txn::UnitOfWorkResult;
use serde_json::{json, Value};

pub fn migrate_format1_outcome_to_json(outcome: &MigrateOutcome) -> Value {
    match outcome {
        MigrateOutcome::AlreadyMigrated { catalog } => json!({
            "migrated": false,
            "catalog": catalog.display().to_string(),
            "tables": [],
            "removedSchemaFiles": [],
        }),
        MigrateOutcome::Migrated {
            catalog,
            tables,
            removed_schema_files,
        } => json!({
            "migrated": true,
            "catalog": catalog.display().to_string(),
            "tables": tables,
            "removedSchemaFiles": removed_schema_files
                .iter()
                .map(|path| path.display().to_string())
                .collect::<Vec<_>>(),
        }),
    }
}

pub fn record_to_json(record: &HaysonRecord) -> Value {
    Value::Object(
        record
            .iter()
            .map(|(field, value)| (field.clone(), value.clone()))
            .collect(),
    )
}

/// The broken markdown links of a record, as the JS side reads them: one object per link, the
/// field it sits in against the virtual path it aimed at. Structured rather than a formatted
/// sentence, so a caller can group by field or retry a target without parsing text apart.
pub fn broken_links_to_json(broken: &[BrokenLink]) -> Value {
    Value::Array(
        broken
            .iter()
            .map(|link| json!({ "field": link.field, "path": link.path }))
            .collect(),
    )
}

fn strategy_name(strategy: QueryStrategy) -> &'static str {
    match strategy {
        QueryStrategy::Primary => "primary",
        QueryStrategy::Exact => "exact",
        QueryStrategy::Sorted => "sorted",
        QueryStrategy::Fulltext => "fulltext",
        QueryStrategy::Union => "union",
        QueryStrategy::Scan => "scan",
    }
}

fn plan_branch_to_json(branch: &PlanBranch) -> Value {
    json!({
        "strategy": strategy_name(branch.strategy),
        "field": branch.field,
        "candidates": branch.candidates,
    })
}

fn overlay_strategy_name(strategy: OverlayStrategy) -> &'static str {
    match strategy {
        OverlayStrategy::Exact => "exact",
        OverlayStrategy::Fulltext => "fulltext",
        OverlayStrategy::Scan => "scan",
    }
}

fn plan_overlay_to_json(overlay: &PlanOverlay) -> Value {
    json!({
        "staged": overlay.staged,
        "suppressed": overlay.suppressed,
        "rescored": overlay.rescored,
        "strategy": overlay_strategy_name(overlay.strategy),
        "size": overlay.size,
    })
}

pub fn plan_to_json(plan: &AccessPathSummary) -> Value {
    json!({
        "strategy": strategy_name(plan.strategy),
        "field": plan.field,
        "index": plan.index,
        "candidates": plan.candidates,
        "ranked": plan.ranked,
        "filteredOnProjection": plan.filtered_on_projection,
        "reads": plan.reads,
        "branches": plan.branches.as_ref().map(|branches| branches.iter().map(plan_branch_to_json).collect::<Vec<_>>()),
        "overlay": plan.overlay.as_ref().map(plan_overlay_to_json),
    })
}

/// The whole answer to `Table.query`: the keys of the page, in query order, the records
/// themselves, how many records matched before `offset`/`limit` cut that page out of them, and the
/// plan that found them — one document rather than a bare array, so the shim can rebuild the
/// `QueryResult` the TS package already exposes without a second round trip for the plan.
pub fn query_result_to_json(
    keys: &[String],
    records: &[HaysonRecord],
    matched: usize,
    plan: &AccessPathSummary,
) -> Value {
    json!({
        "keys": keys,
        "records": records.iter().map(record_to_json).collect::<Vec<_>>(),
        "matched": matched,
        "plan": plan_to_json(plan),
    })
}

/// The answer to a `getMany`: one entry per key the caller asked for, in that order, `null` where
/// the table holds no record — so the caller can zip it against its own key list without a second
/// lookup for which key went missing.
pub fn optional_records_to_json(records: &[Option<HaysonRecord>]) -> Value {
    Value::Array(
        records
            .iter()
            .map(|record| record.as_ref().map(record_to_json).unwrap_or(Value::Null))
            .collect(),
    )
}

/// The whole answer to committing a unit of work, in the shape the TS `UnitOfWorkResult` declares.
/// `tables` is what the unit actually touched, which includes tables reached only by a trigger
/// effect and not named by any staged operation.
pub fn unit_of_work_result_to_json(result: &UnitOfWorkResult) -> Value {
    json!({ "id": result.id, "tables": result.tables, "operations": result.operations })
}

pub fn relation_to_json(relation: &Relation) -> Value {
    json!({
        "name": relation.name,
        "from": { "table": relation.from.table, "field": relation.from.field },
        "to": { "table": relation.to.table, "field": relation.to.field },
        "cardinality": relation.cardinality.as_str(),
        "onDelete": relation.on_delete.map(|action| action.as_str()),
        "enforce": relation.enforce,
    })
}

pub fn relations_to_json(relations: &[Relation]) -> Value {
    Value::Array(relations.iter().map(relation_to_json).collect())
}

fn orphan_record_to_json(orphan: &OrphanRecord) -> Value {
    json!({
        "relation": orphan.relation,
        "table": orphan.table,
        "field": orphan.field,
        "primaryKey": orphan.primary_key,
        "value": orphan.value,
    })
}

pub fn integrity_report_to_json(report: &IntegrityReport) -> Value {
    json!({ "orphans": report.orphans.iter().map(orphan_record_to_json).collect::<Vec<_>>() })
}

/// The counters of `Table.stats()`, in the member names the TS `TableStats` already uses.
/// Where a database keeps its files, in the shape of the TS `Database.layout` property — the
/// deprecated aliases (`catalogFile`/`catalog`/`manifestFile`/`manifest`) carried alongside the
/// current names, holding the same values, because the TS shim reports them all.
pub fn layout_to_json(layout: &Layout) -> Value {
    let metadata_file = layout.metadata_file();
    let metadata_path = layout.metadata_path().display().to_string();
    json!({
        "kind": layout.kind().as_str(),
        "root": layout.root().display().to_string(),
        "metadataFile": metadata_file,
        "metadataPath": metadata_path,
        "catalogFile": metadata_file,
        "catalog": metadata_path,
        "manifestFile": metadata_file,
        "manifest": metadata_path,
        "tables": layout.tables().display().to_string(),
        "indexes": layout.indexes().display().to_string(),
        "runtime": layout.runtime().display().to_string(),
        "lock": layout.lock_path().display().to_string(),
        "journal": layout.journal_path().display().to_string(),
    })
}

/// What `migrateLayout()` answers with, in the shape of the TS `LayoutMigrationResult`. Every path
/// crosses as the engine spelled it, which on the WASM binding is a path inside the module's
/// preopened namespace — the shim rewrites those into host paths, as it already does for a refusal.
pub fn layout_migration_to_json(result: &LayoutMigrationResult) -> Value {
    json!({
        "root": result.root.display().to_string(),
        "from": result.from.as_str(),
        "to": result.to.as_str(),
        "moves": result
            .moves
            .iter()
            .map(|step| json!({ "from": step.from.display().to_string(), "to": step.to.display().to_string() }))
            .collect::<Vec<_>>(),
        "unclaimed": result
            .unclaimed
            .iter()
            .map(|path| path.display().to_string())
            .collect::<Vec<_>>(),
        "changed": result.changed,
        "dryRun": result.dry_run,
    })
}

pub fn table_stats_to_json(stats: &TableStats) -> Value {
    json!({
        "records": stats.records,
        "liveBytes": stats.live_bytes,
        "deadBytes": stats.dead_bytes,
        "logBytes": stats.log_bytes,
        "queueDepth": stats.queue_depth,
        "gen": stats.gen,
        "seq": stats.seq,
    })
}

/// What a `Table.refresh()` found. `changed` is the boolean the TS `Table.refresh()` answers with;
/// `outcome` and `entries` say how it got there, which is what tells a caller apart the cheap
/// catch-up from the rebuild a foreign compaction forces.
pub fn refresh_outcome_to_json(outcome: RefreshOutcome) -> Value {
    let (name, entries) = match outcome {
        RefreshOutcome::Unchanged => ("unchanged", 0),
        RefreshOutcome::CaughtUp { entries } => ("caughtUp", entries),
        RefreshOutcome::Reloaded => ("reloaded", 0),
    };
    json!({ "changed": outcome.changed(), "outcome": name, "entries": entries })
}

/// What a `Table.rotateCypherKeys()` did — records, not fields, and the three outcomes apart, so a
/// caller can tell "nothing to do" from "a record was left behind for want of its key".
pub fn rotation_result_to_json(result: &RotationResult) -> Value {
    json!({
        "rotated": result.rotated,
        "alreadyCurrent": result.already_current,
        "skipped": result.skipped,
    })
}

// NOTE: `slots` is dropped on purpose — an internal remap detail, not a caller-facing stat.
pub fn compaction_result_to_json(result: &CompactionResult) -> Value {
    json!({
        "records": result.records,
        "bytesBefore": result.bytes_before,
        "bytesAfter": result.bytes_after,
        "reclaimedBytes": result.reclaimed_bytes,
    })
}

#[cfg(test)]
mod tests {
    use hayson_engine::catalog::{RelationCardinality, RelationEnd};

    use super::*;

    #[test]
    fn a_query_result_carries_keys_records_the_match_count_and_the_plan_in_one_document() {
        let mut record = HaysonRecord::new();
        record.insert("id".into(), json!("u1"));
        record.insert("name".into(), json!("Ania"));
        let plan = AccessPathSummary {
            strategy: QueryStrategy::Exact,
            field: Some("email".into()),
            index: Some("users_email".into()),
            candidates: 1,
            ranked: false,
            filtered_on_projection: true,
            overlay: None,
            reads: 1,
            branches: None,
        };

        let described = query_result_to_json(&["u1".to_string()], &[record], 7, &plan);

        assert_eq!(described["keys"], json!(["u1"]));
        assert_eq!(described["records"], json!([{ "id": "u1", "name": "Ania" }]));
        assert_eq!(
            described["matched"],
            json!(7),
            "the page is one key wide, the match count is not"
        );
        assert_eq!(described["plan"]["strategy"], json!("exact"));
        assert_eq!(described["plan"]["index"], json!("users_email"));
        assert_eq!(described["plan"]["branches"], Value::Null);
    }

    #[test]
    fn a_plan_carries_ranked_and_filtered_on_projection_under_the_names_the_ts_query_plan_declares() {
        let plan = AccessPathSummary {
            strategy: QueryStrategy::Fulltext,
            field: None,
            index: None,
            candidates: 2,
            ranked: true,
            filtered_on_projection: false,
            overlay: None,
            reads: 2,
            branches: None,
        };

        let described = plan_to_json(&plan);

        assert_eq!(described["ranked"], json!(true));
        assert_eq!(described["filteredOnProjection"], json!(false));
    }

    #[test]
    fn every_query_strategy_has_a_lower_case_name_the_ts_union_already_uses() {
        let all = [
            QueryStrategy::Primary,
            QueryStrategy::Exact,
            QueryStrategy::Sorted,
            QueryStrategy::Fulltext,
            QueryStrategy::Union,
            QueryStrategy::Scan,
        ];
        let names: Vec<&str> = all.into_iter().map(strategy_name).collect();

        assert_eq!(names, vec!["primary", "exact", "sorted", "fulltext", "union", "scan"]);
    }

    #[test]
    fn a_relation_is_flattened_into_the_shape_the_ts_relation_type_declares() {
        let relation = Relation {
            name: "orders_user".into(),
            from: RelationEnd {
                table: "orders".into(),
                field: "userId".into(),
            },
            to: RelationEnd {
                table: "users".into(),
                field: "id".into(),
            },
            cardinality: RelationCardinality::ManyToOne,
            on_delete: None,
            enforce: Some(true),
        };

        let described = relations_to_json(&[relation]);

        assert_eq!(described[0]["from"], json!({ "table": "orders", "field": "userId" }));
        assert_eq!(described[0]["onDelete"], Value::Null);
        assert_eq!(described[0]["enforce"], json!(true));
    }

    #[test]
    fn a_get_many_answer_keeps_a_hole_where_the_table_held_no_record() {
        let mut record = HaysonRecord::new();
        record.insert("id".into(), json!("u1"));

        let described = optional_records_to_json(&[None, Some(record), None]);

        assert_eq!(described, json!([Value::Null, { "id": "u1" }, Value::Null]));
    }

    #[test]
    fn a_committed_unit_reports_the_id_the_tables_and_how_many_operations_it_carried() {
        let result = UnitOfWorkResult {
            id: "42-1-0".into(),
            tables: vec!["users".into(), "audit".into()],
            operations: 3,
        };

        let described = unit_of_work_result_to_json(&result);

        assert_eq!(
            described,
            json!({ "id": "42-1-0", "tables": ["users", "audit"], "operations": 3 })
        );
    }

    #[test]
    fn table_stats_cross_the_boundary_under_the_camel_case_names_the_ts_type_declares() {
        let stats = TableStats {
            records: 2,
            live_bytes: 40,
            dead_bytes: 10,
            log_bytes: 50,
            queue_depth: 0,
            gen: 1,
            seq: 7,
        };

        let described = table_stats_to_json(&stats);

        assert_eq!(
            described,
            json!({ "records": 2, "liveBytes": 40, "deadBytes": 10, "logBytes": 50, "queueDepth": 0, "gen": 1, "seq": 7 })
        );
    }

    #[test]
    fn each_refresh_outcome_names_itself_and_agrees_with_its_own_changed_flag() {
        let unchanged = refresh_outcome_to_json(RefreshOutcome::Unchanged);
        let caught_up = refresh_outcome_to_json(RefreshOutcome::CaughtUp { entries: 3 });
        let reloaded = refresh_outcome_to_json(RefreshOutcome::Reloaded);

        assert_eq!(
            unchanged,
            json!({ "changed": false, "outcome": "unchanged", "entries": 0 })
        );
        assert_eq!(
            caught_up,
            json!({ "changed": true, "outcome": "caughtUp", "entries": 3 })
        );
        assert_eq!(
            reloaded,
            json!({ "changed": true, "outcome": "reloaded", "entries": 0 })
        );
    }

    #[test]
    fn a_record_keeps_its_field_order_across_the_boundary() {
        let mut record = HaysonRecord::new();
        record.insert("id".into(), json!("u1"));
        record.insert("age".into(), json!(31));

        let text = record_to_json(&record).to_string();

        assert_eq!(
            text, r#"{"age":31,"id":"u1"}"#,
            "HaysonRecord is a BTreeMap — field order is its key order"
        );
    }
}