Skip to main content

core_api/
lib.rs

1pub mod algo;
2mod db;
3pub mod history;
4mod ingest;
5pub mod mask;
6pub mod reader;
7pub mod roles;
8pub mod schema;
9mod shared;
10pub mod subscription;
11
12pub use algo::{
13    AlgoDir, DegreeConfig, DegreeReport, PageRankConfig, PageRankReport, WccConfig, WccReport,
14};
15pub use core_query::{CmpOp, Dir, Filter, ResultSet};
16pub use core_rules::suggest::DEFAULT_SEED as SUGGEST_DEFAULT_SEED;
17pub use core_rules::{
18    default_max_edges, is_keymatch_rooted, AggFn, Predicate, RuleDef, RuleSuggestion,
19    SuggestConfig, SuggestReport, ViewDef, ViewSource, ViewStore, DEFAULT_KEYMATCH_TOP_K,
20    DEFAULT_SCORED_TOP_K, MAX_CHAIN_DEPTH,
21};
22pub use core_storage::{Direction, GraphError, Result, Value};
23pub use db::{query_sub_exec_count, reset_query_sub_exec_count};
24pub use db::{
25    snapshot_version_at, write_snapshot_bak, BackupReport, BatchBuilder, BatchOp, DeleteReport,
26    EdgeInfo, Explanation, ExportEdge, FsyncPolicy, GraphDb, MaskedEdge, MaskedNodeResult,
27    MutationEvent, NodeInfo, NodeRef, OpenOptions, Precondition, PredicateSummary, RuleStats,
28    SlowQueryEntry, SlowQuerySnapshot, SnapshotOptions, Stats, WriteAuthz,
29};
30
31/// Current on-disk snapshot format version written by this build.
32///
33/// Exposed so CLI and tooling can print `V<SNAPSHOT_VERSION>` without depending
34/// directly on `core-storage`.
35pub const SNAPSHOT_VERSION: u16 = core_storage::snapshot::VERSION;
36pub use history::{EdgeEvent, EdgeHistoryEvent, HistoryChange, HistoryEntry, HistoryResult};
37pub use ingest::{
38    json_to_rows, json_to_value, AutoFk, FkSkip, IngestOptions, IngestReport, JsonRows,
39};
40pub use mask::{MaskMode, NodeMask};
41pub use reader::{CommitDelta, FrozenOverlay, ReaderSnapshot, FOLD_EVERY_K};
42pub use roles::{RoleDef, WriteScope};
43pub use schema::{Schema, SchemaDiff};
44pub use shared::SharedDb;
45pub use subscription::{DbEvent, Subscription, DEFAULT_SUB_CAPACITY};
46
47/// One verification entry per section: `(section_id, section_name, bytes_checked, result)`.
48///
49/// Returned by [`verify_snapshot`].
50pub type SectionVerifyResult = (u8, &'static str, usize, std::result::Result<(), String>);
51
52/// Validate the CRC32 integrity of every section in the V8 snapshot at `dir`.
53///
54/// Returns one entry per section directory entry (see [`SectionVerifyResult`]).
55///
56/// Large sections (TOPOLOGY, COLUMNS, EDGE_PROPS, HNSW, PROVENANCE, IVF_STATE)
57/// skip CRC on the normal hot query path; this function always checks them.
58/// Use it to implement `mushroomdb verify` without depending on `core-storage`
59/// directly.
60pub fn verify_snapshot(dir: &std::path::Path) -> crate::Result<Vec<SectionVerifyResult>> {
61    let snap_path = dir.join("snapshot.bin");
62    let mapped = core_storage::v8::MappedBase::map(&snap_path)?;
63    // Bounds first, then per-section CRC32, then a structural (rkyv bytecheck)
64    // pass over the sections the hot path reads unchecked. The structural pass
65    // rejects a maliciously crafted snapshot whose relative pointers would
66    // otherwise trigger UB on open — a threat CRC32 alone can't catch (an
67    // attacker can recompute the CRC). Fail loud on structural corruption.
68    mapped.validate_section_bounds()?;
69    let results = mapped.verify_integrity();
70    mapped.validate_hot_sections()?;
71    Ok(results)
72}
73
74/// Return `true` if `cypher` is a write statement (CREATE / MERGE / MATCH…SET /
75/// MATCH…DELETE).  Returns `Err` only when the string fails to lex.
76///
77/// Used by the HTTP server to dispatch to the write lock without a full parse.
78pub fn is_write_query(cypher: &str) -> std::result::Result<bool, String> {
79    let toks = core_query::cypher::lex(cypher).map_err(|e| format!("lex: {e}"))?;
80    Ok(core_query::cypher::is_write_tokens(&toks))
81}
82
83/// Return the number of valid WAL commits in the database at `dir`.
84///
85/// Useful for displaying "as-of commit N of M" in CLIs without opening the
86/// full database.  Returns 0 if the WAL file does not exist (e.g., after
87/// `snapshot()` which truncates it to empty).
88pub fn wal_commit_count_at(dir: &std::path::Path) -> crate::Result<u64> {
89    let wal_path = dir.join("wal.bin");
90    let bytes = match std::fs::read(&wal_path) {
91        Ok(b) => b,
92        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Vec::new(),
93        Err(e) => return Err(core_storage::GraphError::Io(e)),
94    };
95    Ok(core_storage::wal::wal_commits(&bytes))
96}