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