Files
marqdo-knowledge/src/storage/mod.rs
marqdo-knowledge 87b9c132aa feat(embedding): explicit OpenAI-compatible semantic channel
- add a transport client for one current backend protocol with loopback http,
  TLS-only remote endpoints, explicit remote consent, disabled redirects,
  bounded timeout/batch/payload/response/dimension and no credential in URLs
- validate responses strictly (count, index order, dimension, finite values,
  non-zero norm, mixed-model rejection) and abort publication when any vector
  is missing so a mixed index is never stored
- embed search units in the same transaction that writes the projection, with
  content-digest/model-digest guarded reuse for incremental compiles; the
  build metadata records endpoint/model/revision/dimension/distance/chunking
- add the semantic query channel behind explicit --semantic using an exact
  cosine scan with a bounded vector budget; default queries stay completely
  offline even when vectors exist
- add a local mock-server integration test proving protocol handling,
  cross-vocabulary recall, offline default behaviour, remote consent rules and
  all-or-nothing failure; real-model quality remains NOT RUN and is not claimed
2026-11-26 02:26:37 +08:00

883 lines
32 KiB
Rust

//! SQLite storage: one derived artifact, one schema revision, one writer.
//!
//! `publish` is the only write path. A full rebuild stages a private database
//! in the target directory and renames it into place; an incremental update
//! rewrites the projection inside one transaction on the existing file. Both
//! share the same writer and only become visible when complete. A failure
//! leaves the previous successful artifact untouched.
pub mod index;
pub mod read;
use crate::diagnostic::{code, Diagnostic};
use crate::document::analysis::ProjectContext;
use crate::document::SourceSnapshot;
use crate::error::KnowledgeError;
use crate::graph::Graph;
use crate::model::{sha256_prefixed, Span};
use rusqlite::{Connection, OpenFlags, Transaction};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
/// On-disk schema revision. Incompatible databases are rejected and require an
/// explicit rebuild; there is no migration.
pub const SCHEMA_REVISION: u32 = 1;
/// SQLite `application_id` marker (ASCII "MKN1").
pub const APPLICATION_ID: i64 = 0x4D4B_4E31;
/// Busy timeout for concurrent writer attempts.
pub const BUSY_TIMEOUT_MS: u32 = 5_000;
/// Maximum database size accepted or produced.
pub const MAX_DATABASE_BYTES: u64 = 4 * 1024 * 1024 * 1024;
const SCHEMA_SQL: &str = include_str!("schema.sql");
/// Build metadata persisted in the singleton row.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BuildMeta {
pub tool_version: String,
pub schema_revision: u32,
pub producer_version: String,
pub core_identity: String,
pub snapshot_digest: String,
pub logical_digest: String,
pub scope: serde_json::Value,
pub options: serde_json::Value,
pub index_config: serde_json::Value,
pub embedding: Option<serde_json::Value>,
pub facts_cache_version: u32,
pub rebuild_generation: u64,
pub complete: bool,
}
impl BuildMeta {
pub fn new(tool_version: &str, snapshot_digest: String, logical_digest: String) -> Self {
Self {
tool_version: tool_version.to_string(),
schema_revision: SCHEMA_REVISION,
producer_version: String::new(),
core_identity: String::new(),
snapshot_digest,
logical_digest,
scope: serde_json::Value::Null,
options: serde_json::Value::Null,
index_config: serde_json::json!({"fts": "unicode61", "grams": [2, 3], "chunk_bytes": 4096}),
embedding: None,
facts_cache_version: 1,
rebuild_generation: 1,
complete: true,
}
}
}
#[derive(Debug, Clone, Default)]
pub struct PublishStats {
pub mode: String,
pub documents: u64,
pub nodes: u64,
pub edges: u64,
pub search_units: u64,
pub grams: u64,
pub embeddings: u64,
pub rebuild_generation: u64,
}
pub struct PublishRequest<'a> {
pub database_path: PathBuf,
pub rebuild: bool,
pub meta: BuildMeta,
pub graph: &'a Graph,
pub snapshot: &'a SourceSnapshot,
pub contexts: &'a [ProjectContext],
pub embeddings: Option<&'a crate::embedding::EmbeddingVectors>,
}
/// Open a connection with the mandatory safety pragmas.
fn configure(conn: &Connection) -> Result<(), KnowledgeError> {
conn.execute_batch(&format!(
"PRAGMA foreign_keys = ON;\nPRAGMA busy_timeout = {BUSY_TIMEOUT_MS};"
))
.map_err(|error| KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string()))
}
/// Open the current database read-only and verify it is ours and current.
pub fn open_read_only(path: &Path) -> Result<Connection, KnowledgeError> {
if !path.is_file() {
return Err(KnowledgeError::environment(
code::DATABASE_MISSING,
"knowledge database does not exist",
)
.with_hint("run `marqdo knowledge compile` for this root"));
}
let metadata = std::fs::metadata(path).map_err(|error| {
KnowledgeError::environment(
code::DATABASE_MISSING,
format!("database cannot be read: {error}"),
)
})?;
if metadata.len() > MAX_DATABASE_BYTES {
return Err(KnowledgeError::environment(
code::BUDGET_EXCEEDED,
"knowledge database exceeds the size budget",
));
}
let conn = Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_ONLY)
.map_err(|error| database_error(path, error))?;
configure(&conn)?;
verify_schema(&conn, path)?;
Ok(conn)
}
/// Verify application id, schema revision, required tables and quick integrity.
pub fn verify_schema(conn: &Connection, path: &Path) -> Result<(), KnowledgeError> {
let application_id: i64 = conn
.query_row("PRAGMA application_id", [], |row| row.get(0))
.map_err(|error| database_error(path, error))?;
if application_id != APPLICATION_ID {
return Err(KnowledgeError::environment(
code::DATABASE_NOT_OURS,
"file is not a marqdo-knowledge database",
)
.with_hint("move the foreign file away; this tool never overwrites unknown databases"));
}
let user_version: i64 = conn
.query_row("PRAGMA user_version", [], |row| row.get(0))
.map_err(|error| database_error(path, error))?;
if user_version != i64::from(SCHEMA_REVISION) {
return Err(KnowledgeError::environment(
code::DATABASE_OLD_SCHEMA,
format!(
"database schema revision {user_version} is not the current revision {SCHEMA_REVISION}"
),
)
.with_hint("run `marqdo knowledge compile --rebuild` to rebuild the derived database"));
}
for table in [
"build",
"documents",
"nodes",
"aliases",
"edges",
"contexts",
"inputs",
"diagnostics",
"search_units",
"search_fts",
"grams",
"embeddings",
] {
let count: i64 = conn
.query_row(
"SELECT count(*) FROM sqlite_master WHERE (name = ?1 AND type IN ('table','view'))",
[table],
|row| row.get(0),
)
.map_err(|error| database_error(path, error))?;
if count != 1 {
return Err(KnowledgeError::environment(
code::DATABASE_CORRUPT,
format!("knowledge database is missing table `{table}`"),
)
.with_hint("run `marqdo knowledge compile --rebuild`"));
}
}
let revision: i64 = conn
.query_row(
"SELECT schema_revision FROM build WHERE id = 1",
[],
|row| row.get(0),
)
.map_err(|error| database_error(path, error))?;
if revision != i64::from(SCHEMA_REVISION) {
return Err(KnowledgeError::environment(
code::DATABASE_OLD_SCHEMA,
"knowledge build metadata uses an incompatible schema revision",
)
.with_hint("run `marqdo knowledge compile --rebuild`"));
}
let check: String = conn
.query_row("PRAGMA quick_check", [], |row| row.get(0))
.map_err(|error| database_error(path, error))?;
if check != "ok" {
return Err(KnowledgeError::environment(
code::DATABASE_CORRUPT,
"knowledge database failed its integrity check",
)
.with_hint("run `marqdo knowledge compile --rebuild`"));
}
Ok(())
}
fn database_error(path: &Path, error: rusqlite::Error) -> KnowledgeError {
let message = error.to_string();
if message.contains("not a database") || message.contains("file is encrypted") {
return KnowledgeError::environment(
code::DATABASE_NOT_OURS,
"file is not a SQLite database this tool created",
)
.with_hint("move the foreign file away; this tool never overwrites unknown databases");
}
let _ = path;
KnowledgeError::environment(code::DATABASE_CORRUPT, format!("database error: {message}"))
}
/// Publish a complete projection. Chooses an atomic rebuild or a transactional
/// incremental rewrite automatically.
pub fn publish(request: PublishRequest<'_>) -> Result<PublishStats, KnowledgeError> {
if request.graph.diagnostics.has_errors() {
return Err(KnowledgeError::input(
code::INTERNAL,
"refusing to publish a graph that contains blocking diagnostics",
));
}
let database_path = request.database_path.clone();
let parent = database_path
.parent()
.ok_or_else(|| KnowledgeError::internal("database path has no parent directory"))?;
std::fs::create_dir_all(parent)?;
set_owner_only_directory(parent);
let exists = database_path.exists();
let rebuild = request.rebuild || !exists;
if rebuild {
ensure_replaceable(&database_path)?;
} else {
// Validate before rewriting.
let conn = open_read_only(&database_path)?;
drop(conn);
}
let mut stats = if rebuild {
publish_rebuild(&request)?
} else {
publish_incremental(&request)?
};
stats.mode = if rebuild {
"rebuild".into()
} else {
"incremental".into()
};
stats.rebuild_generation = request.meta.rebuild_generation;
Ok(stats)
}
fn publish_rebuild(request: &PublishRequest<'_>) -> Result<PublishStats, KnowledgeError> {
let database_path = &request.database_path;
let parent = database_path
.parent()
.ok_or_else(|| KnowledgeError::internal("database path has no parent directory"))?;
let temp_path = temp_database_path(parent);
let _cleanup = TempFileGuard {
path: temp_path.clone(),
};
let mut conn = Connection::open(&temp_path).map_err(|error| {
KnowledgeError::environment(code::IO, format!("cannot create staging database: {error}"))
})?;
configure(&conn)?;
conn.execute_batch(SCHEMA_SQL)
.map_err(|error| KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string()))?;
conn.execute_batch(&format!(
"PRAGMA application_id = {APPLICATION_ID};\nPRAGMA user_version = {SCHEMA_REVISION};"
))
.map_err(|error| KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string()))?;
let mut meta = request.meta.clone();
meta.rebuild_generation = if request.meta.rebuild_generation == 0 {
1
} else {
request.meta.rebuild_generation
};
meta.complete = true;
let stats = write_projection(&mut conn, request, &meta)?;
// Verify before publishing.
let check: String = conn
.query_row("PRAGMA quick_check", [], |row| row.get(0))
.map_err(|error| KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string()))?;
if check != "ok" {
return Err(KnowledgeError::environment(
code::DATABASE_CORRUPT,
"staged database failed its integrity check; nothing was published",
));
}
drop(conn);
set_owner_only_file(&temp_path);
// Re-check the target is still safe, then replace atomically.
ensure_replaceable(database_path)?;
std::fs::rename(&temp_path, database_path).map_err(|error| {
KnowledgeError::environment(code::IO, format!("cannot publish database: {error}"))
})?;
set_owner_only_file(database_path);
Ok(stats)
}
fn publish_incremental(request: &PublishRequest<'_>) -> Result<PublishStats, KnowledgeError> {
let database_path = &request.database_path;
let mut conn = Connection::open(database_path).map_err(|error| {
KnowledgeError::environment(
code::IO,
format!("cannot open database for update: {error}"),
)
})?;
configure(&conn)?;
verify_schema(&conn, database_path)?;
// Rollback journal keeps the single persistent artifact self-contained.
conn.execute_batch("PRAGMA journal_mode = DELETE;")
.map_err(|error| KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string()))?;
let transaction = conn.transaction().map_err(|error| {
KnowledgeError::environment(
code::DATABASE_CORRUPT,
format!("cannot start transaction: {error}"),
)
})?;
// Derived content is replaced atomically. Re-analysis is avoided by the
// compiler's digest-guarded facts cache; the write set is the full
// projection, which keeps incremental semantics equal to a full build.
transaction
.execute_batch(
"INSERT INTO search_fts(search_fts) VALUES('delete-all');
DELETE FROM embeddings;
DELETE FROM grams;
DELETE FROM search_units;
DELETE FROM edges;
DELETE FROM aliases;
DELETE FROM nodes;
DELETE FROM documents;
DELETE FROM contexts;
DELETE FROM inputs;
DELETE FROM diagnostics;
DELETE FROM build;",
)
.map_err(|error| KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string()))?;
let mut meta = request.meta.clone();
meta.rebuild_generation = request.meta.rebuild_generation;
meta.complete = false;
insert_build(&transaction, &meta)?;
let stats = write_rows(&transaction, request, &meta)?;
transaction
.execute("UPDATE build SET complete = 1 WHERE id = 1", [])
.map_err(|error| KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string()))?;
transaction.commit().map_err(|error| {
KnowledgeError::environment(code::DATABASE_CORRUPT, format!("commit failed: {error}"))
})?;
let check: String = conn
.query_row("PRAGMA quick_check", [], |row| row.get(0))
.map_err(|error| KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string()))?;
if check != "ok" {
return Err(KnowledgeError::environment(
code::DATABASE_CORRUPT,
"updated database failed its integrity check",
));
}
Ok(stats)
}
fn write_projection(
conn: &mut Connection,
request: &PublishRequest<'_>,
meta: &BuildMeta,
) -> Result<PublishStats, KnowledgeError> {
let transaction = conn.transaction().map_err(|error| {
KnowledgeError::environment(
code::DATABASE_CORRUPT,
format!("cannot start transaction: {error}"),
)
})?;
insert_build(&transaction, meta)?;
let stats = write_rows(&transaction, request, meta)?;
transaction.commit().map_err(|error| {
KnowledgeError::environment(code::DATABASE_CORRUPT, format!("commit failed: {error}"))
})?;
Ok(stats)
}
fn insert_build(transaction: &Transaction<'_>, meta: &BuildMeta) -> Result<(), KnowledgeError> {
transaction
.execute(
"INSERT INTO build
(id, schema_revision, application_id, tool_version, producer_version,
core_identity, snapshot_digest, logical_digest, scope_json, options_json,
index_config_json, embedding_json, facts_cache_version,
rebuild_generation, complete)
VALUES (1, ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)",
rusqlite::params![
i64::from(meta.schema_revision),
APPLICATION_ID,
meta.tool_version,
meta.producer_version,
meta.core_identity,
meta.snapshot_digest,
meta.logical_digest,
serde_json::to_string(&meta.scope).unwrap_or_else(|_| "null".into()),
serde_json::to_string(&meta.options).unwrap_or_else(|_| "null".into()),
serde_json::to_string(&meta.index_config).unwrap_or_else(|_| "null".into()),
meta.embedding
.as_ref()
.map(|embedding| serde_json::to_string(embedding)
.unwrap_or_else(|_| "null".into())),
i64::from(meta.facts_cache_version),
meta.rebuild_generation as i64,
i64::from(meta.complete),
],
)
.map_err(|error| KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string()))?;
Ok(())
}
fn write_rows(
transaction: &Transaction<'_>,
request: &PublishRequest<'_>,
meta: &BuildMeta,
) -> Result<PublishStats, KnowledgeError> {
let mut stats = PublishStats::default();
// Documents.
let mut doc_ids: HashMap<&str, i64> = HashMap::new();
for facts in &request.graph.facts {
let Some(file) = request
.snapshot
.files
.iter()
.find(|file| file.rel_path == facts.rel_path)
else {
return Err(KnowledgeError::input(
code::INTERNAL,
format!("document `{}` has no source snapshot entry", facts.rel_path),
));
};
let facts_json = serde_json::to_string(facts).map_err(|error| {
KnowledgeError::internal(format!("cannot serialise document facts: {error}"))
})?;
let facts_digest = sha256_prefixed(facts_json.as_bytes());
let front_matter = facts
.front_matter
.as_ref()
.and_then(|front_matter| front_matter.value.as_ref())
.map(|value| serde_json::to_string(value).unwrap_or_else(|_| "null".into()));
let status = if facts.diagnostics.has_errors() {
"warnings"
} else if facts.diagnostics.is_empty() {
"ok"
} else {
"warnings"
};
transaction
.execute(
"INSERT INTO documents
(path, format, source_digest, source, title, front_matter_json,
document_role, okf_json, analysis_context_id, module_id,
facts_json, facts_digest, facts_cache_version, diagnostic_status)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)",
rusqlite::params![
facts.rel_path,
facts.format.as_str(),
facts.source_digest,
file.text.as_bytes(),
facts.document_title,
front_matter,
facts.okf.role.as_str(),
serde_json::to_string(&facts.okf).unwrap_or_else(|_| "null".into()),
facts
.analysis
.as_ref()
.map(|analysis| analysis.context_id.clone()),
facts
.analysis
.as_ref()
.map(|analysis| analysis.module_id.clone()),
facts_json,
facts_digest,
i64::from(meta.facts_cache_version),
status,
],
)
.map_err(|error| {
KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string())
})?;
doc_ids.insert(facts.rel_path.as_str(), transaction.last_insert_rowid());
stats.documents += 1;
}
// Nodes (parents updated in a second pass so insertion order is irrelevant).
let mut node_ids: HashMap<&str, i64> = HashMap::new();
for node in &request.graph.nodes {
let doc_id = if node.doc_path.is_empty() {
None
} else {
doc_ids.get(node.doc_path.as_str()).copied()
};
let title_norm = crate::text::normalize(&node.title);
let symbol_norm = node
.metadata
.get("local_name")
.and_then(|value| value.as_str())
.map(crate::text::normalize);
transaction
.execute(
"INSERT INTO nodes
(canonical_key, kind, doc_id, parent_id, span_start, span_end,
title, title_norm, symbol_norm, content_digest, semantic_digest,
searchable, metadata_json)
VALUES (?1, ?2, ?3, NULL, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
rusqlite::params![
node.key.as_str(),
node.kind.as_str(),
doc_id,
node.span.map(|span| span.start as i64),
node.span.map(|span| span.end as i64),
node.title,
title_norm,
symbol_norm,
node.content_digest,
node.semantic_digest,
i64::from(node.is_searchable()),
serde_json::to_string(&node.metadata).unwrap_or_else(|_| "null".into()),
],
)
.map_err(|error| {
KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string())
})?;
node_ids.insert(node.key.as_str(), transaction.last_insert_rowid());
stats.nodes += 1;
}
for node in &request.graph.nodes {
let Some(parent) = &node.parent else {
continue;
};
let (Some(node_id), Some(parent_id)) = (
node_ids.get(node.key.as_str()),
node_ids.get(parent.as_str()),
) else {
return Err(KnowledgeError::internal(
"node parent is missing during publication",
));
};
transaction
.execute(
"UPDATE nodes SET parent_id = ?1 WHERE id = ?2",
rusqlite::params![parent_id, node_id],
)
.map_err(|error| {
KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string())
})?;
}
// Aliases.
for alias in &request.graph.aliases {
let Some(node_id) = node_ids.get(alias.node.as_str()) else {
return Err(KnowledgeError::internal(
"alias node is missing during publication",
));
};
transaction
.execute(
"INSERT INTO aliases (alias, context_id, node_id) VALUES (?1, ?2, ?3)",
rusqlite::params![
alias.alias,
alias.context.clone().unwrap_or_default(),
node_id
],
)
.map_err(|error| {
KnowledgeError::environment(
code::INTERFACE_CONFLICT,
format!("alias cannot be stored unambiguously: {error}"),
)
})?;
}
// Edges.
for edge in &request.graph.edges {
let Some(source_id) = node_ids.get(edge.source.as_str()).copied() else {
return Err(KnowledgeError::internal(
"edge source is missing during publication",
));
};
let target_id = match &edge.target {
Some(target) => Some(*node_ids.get(target.as_str()).ok_or_else(|| {
KnowledgeError::internal("edge target is missing during publication")
})?),
None => None,
};
let doc_id = doc_ids.get(edge.doc_path.as_str()).copied();
transaction
.execute(
"INSERT INTO edges
(source_id, target_id, kind, origin, raw_target, span_start, span_end,
doc_id, state, context_id)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
rusqlite::params![
source_id,
target_id,
edge.kind.as_str(),
edge.origin.as_str(),
edge.raw_target,
edge.span.map(|span| span.start as i64),
edge.span.map(|span| span.end as i64),
doc_id,
edge.state.as_str(),
edge.context,
],
)
.map_err(|error| {
KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string())
})?;
stats.edges += 1;
}
// Analysis contexts.
for context in request.contexts {
transaction
.execute(
"INSERT OR IGNORE INTO contexts
(context_id, entry_module_id, root_id, identity_kind, manifest_digest,
lock_digest, stdlib_digest, producer_version, analysis_digest, extensions_json)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
rusqlite::params![
context.context_id,
context.entry_module_id,
context.root_id,
context.identity_kind,
context.manifest_digest,
context.lock_digest,
context.stdlib_digest,
context.producer_version,
context.analysis_digest,
serde_json::to_string(&context.extensions).unwrap_or_else(|_| "null".into()),
],
)
.map_err(|error| {
KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string())
})?;
}
// Input snapshot.
for input in request.snapshot.inputs() {
transaction
.execute(
"INSERT OR REPLACE INTO inputs (path, kind, digest, size) VALUES (?1, ?2, ?3, ?4)",
rusqlite::params![
input.path,
input.kind.as_str(),
input.digest,
input.size as i64
],
)
.map_err(|error| {
KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string())
})?;
}
// Diagnostics (also those discovered by the graph layer).
for diagnostic in request.graph.diagnostics.iter() {
insert_diagnostic(transaction, diagnostic)?;
}
for diagnostic in request.snapshot.diagnostics.iter() {
insert_diagnostic(transaction, diagnostic)?;
}
let index_stats = index::build_index(
transaction,
request.graph,
&doc_ids,
&node_ids,
request.embeddings,
)?;
stats.search_units = index_stats.search_units;
stats.grams = index_stats.grams;
stats.embeddings = index_stats.embeddings;
Ok(stats)
}
fn insert_diagnostic(
transaction: &Transaction<'_>,
diagnostic: &Diagnostic,
) -> Result<(), KnowledgeError> {
transaction
.execute(
"INSERT INTO diagnostics
(code, severity, path, span_start, span_end, message, hints_json)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
rusqlite::params![
diagnostic.code,
diagnostic.severity.as_str(),
diagnostic.path,
diagnostic.span.map(|span| span.start as i64),
diagnostic.span.map(|span| span.end as i64),
diagnostic.message,
serde_json::to_string(&diagnostic.hints).unwrap_or_else(|_| "[]".into()),
],
)
.map_err(|error| KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string()))?;
Ok(())
}
fn ensure_replaceable(database_path: &Path) -> Result<(), KnowledgeError> {
match std::fs::symlink_metadata(database_path) {
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(KnowledgeError::environment(
code::IO,
format!("database path cannot be inspected: {error}"),
)),
Ok(metadata) if metadata.file_type().is_symlink() => Err(KnowledgeError::environment(
code::DATABASE_NOT_OURS,
"database path is a symbolic link; refusing to replace it",
)),
Ok(metadata) if !metadata.is_file() => Err(KnowledgeError::environment(
code::DATABASE_NOT_OURS,
"database path is not a regular file; refusing to replace it",
)),
Ok(_) => {
// Only replace a database this tool created.
let conn = Connection::open_with_flags(database_path, OpenFlags::SQLITE_OPEN_READ_ONLY)
.map_err(|error| database_error(database_path, error))?;
let application_id: i64 = conn
.query_row("PRAGMA application_id", [], |row| row.get(0))
.map_err(|error| database_error(database_path, error))?;
if application_id != APPLICATION_ID {
return Err(KnowledgeError::environment(
code::DATABASE_NOT_OURS,
"existing database was not created by this tool; refusing to overwrite it",
)
.with_hint("move the foreign file away manually"));
}
Ok(())
}
}
}
fn temp_database_path(parent: &Path) -> PathBuf {
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(0);
let counter = COUNTER.fetch_add(1, Ordering::Relaxed);
parent.join(format!(
".knowledge.sqlite.tmp.{}.{}",
std::process::id(),
counter
))
}
struct TempFileGuard {
path: PathBuf,
}
impl Drop for TempFileGuard {
fn drop(&mut self) {
if self.path.exists() {
let _ = std::fs::remove_file(&self.path);
let _ = std::fs::remove_file(self.path.with_extension("sqlite-journal"));
}
}
}
#[cfg(unix)]
fn set_owner_only_directory(path: &Path) {
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700));
}
#[cfg(not(unix))]
fn set_owner_only_directory(_path: &Path) {}
#[cfg(unix)]
fn set_owner_only_file(path: &Path) {
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
}
#[cfg(not(unix))]
fn set_owner_only_file(_path: &Path) {}
/// Currentness of the stored snapshot relative to the current source inputs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Currentness {
pub current: bool,
pub snapshot_digest: String,
pub stored_snapshot_digest: String,
pub changed_inputs: Vec<String>,
}
/// Compare the stored input manifest with the current source snapshot.
pub fn check_current(
conn: &Connection,
snapshot: &SourceSnapshot,
) -> Result<Currentness, KnowledgeError> {
let stored_snapshot_digest: String = conn
.query_row(
"SELECT snapshot_digest FROM build WHERE id = 1",
[],
|row| row.get(0),
)
.map_err(|error| KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string()))?;
let mut stored_inputs: HashMap<String, String> = HashMap::new();
{
let mut statement = conn
.prepare("SELECT path, digest FROM inputs")
.map_err(|error| {
KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string())
})?;
let rows = statement
.query_map([], |row| {
Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
})
.map_err(|error| {
KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string())
})?;
for row in rows {
let (path, digest) = row.map_err(|error| {
KnowledgeError::environment(code::DATABASE_CORRUPT, error.to_string())
})?;
stored_inputs.insert(path, digest);
}
}
let current_inputs = snapshot.inputs();
let current_digest = snapshot.snapshot_digest();
let mut changed = Vec::new();
for input in &current_inputs {
match stored_inputs.get(&input.path) {
Some(digest) if digest == &input.digest => {}
_ => changed.push(input.path.clone()),
}
}
for path in stored_inputs.keys() {
if !current_inputs.iter().any(|input| &input.path == path) {
changed.push(path.clone());
}
}
changed.sort();
changed.dedup();
Ok(Currentness {
current: changed.is_empty() && current_digest == stored_snapshot_digest,
snapshot_digest: current_digest,
stored_snapshot_digest,
changed_inputs: changed,
})
}
/// Read one stored span as an exact source slice (used for snippets and
/// slices). Returns `None` for invalid ranges.
pub fn source_slice(source: &[u8], span: Span) -> Option<&str> {
span.slice(source)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn application_id_marker_is_stable() {
assert_eq!(APPLICATION_ID, 0x4D4B_4E31);
assert_eq!(SCHEMA_REVISION, 1);
}
#[test]
fn temp_database_paths_are_unique_and_sibling() {
let parent = Path::new("/tmp/example");
let first = temp_database_path(parent);
let second = temp_database_path(parent);
assert_ne!(first, second);
assert_eq!(first.parent(), Some(parent));
assert!(first
.file_name()
.unwrap()
.to_string_lossy()
.starts_with(".knowledge.sqlite.tmp."));
}
}