Skip to main content

core_api/
lib.rs

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