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