Files
Thing/src-tauri/src/editor/index_service.rs
T
2026-10-10 14:29:48 +08:00

593 lines
25 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! 索引服务:单线程 worker + notify 文件监听。
//!
//! # 为什么索引必须由一个线程独占
//!
//! `rusqlite::Connection` 不是 `Sync` 的共享对象,而本模块有三个**并发**入口:
//! ① 前端的搜索/统计命令(Tauri 命令线程池,可能同时进来好几个);
//! ② 保存笔记后的增量更新;③ 文件监听器(notify 自己的回调线程)。
//!
//! 三种做法各有代价:给连接套 `Mutex` 会让「全库重建索引」这类慢操作**堵住搜索**
//! (UI 直接卡住);每次操作现开一个连接则丢失 prepared statement 缓存,还会在
//! WAL 上堆出一串写锁竞争。这里选第三条:**一个专职线程独占连接**,所有操作通过
//! 消息通道排队进来。慢操作只排队、不阻塞调用方(命令层是异步等待回复),
//! 连接始终只有一个,顺序天然可预期。
//!
//! # 监听器为什么也挂在这个线程上
//!
//! `notify` 的事件要落到索引上(外部新增/改动文件后立刻可搜),而**只有这个线程
//! 能写索引**。让监听回调投递一条 `SyncPath` 消息给 worker,就地把那一个文件同步掉,
//! 比「回调里发前端事件 → 前端再调一次同步命令」少一次往返,也不会因为前端窗口
//! 关着而漏掉索引更新。
//!
//! 自我保存识别([`SUPPRESS_MS`])是必须的:编辑器每次自动保存都会触发
//! `Modify(Data)`,若把这类事件也当成「外部修改」,前端就会在用户自己打字时反复
//! 重载文档 / 弹提示。识别按**库内相对路径**在写入前登记(见 `mark_write_path`),
//! 结果写进事件的 `from_app`,由前端决定是否提示 —— 而不是在这里静默丢弃事件。
//! 静默丢弃一旦因时序漏判,前端就会把自家的保存当成外部改动而重载。
use std::path::{Path, PathBuf};
use std::sync::mpsc::{self, Receiver, Sender};
use std::sync::Mutex;
use std::time::{Duration, Instant};
use notify::{EventKind, RecommendedWatcher, RecursiveMode, Watcher};
use serde::Serialize;
use specta::Type;
use tauri::{AppHandle, Emitter};
use super::files;
use super::index::{content_hash, NoteIndexStats, NoteSearchHit, NoteSearchPage, NoteSearchQuery, NoteSyncReport, EditorIndex};
use super::library;
use crate::constants::events;
/// 自我写入(自己刚保存)与外部改动之间的**去重窗口**。
///
/// 取 1200ms:一次写入可能被 notify 拆成多条事件(`Modify(Data)` 常伴一条元数据事件),
/// 命中的第一条之后,这段时间内的同路径事件一并算作「自己写的」,既不重复处理,
/// 又不会把窗口拉得太长去吞掉用户紧接着在外部编辑器里的另一次保存。
const SUPPRESS_MS: u64 = 1200;
/// 自我写入登记在「尚未被任何文件事件命中」时的最长存活时间。
///
/// 比去重窗口宽得多:notify 的派发延迟可能到秒级,窗口太窄会把「自己刚写的」误判成
/// 外部修改(重载文档、光标弹回第一行)—— 这正是要避免的事故。登记项一旦被**第一个**
/// 匹配事件消费,就只保留 [`SUPPRESS_MS`] 的去重窗口,不会长期吞掉真正的外部改动。
const SELF_WRITE_TTL_MS: u64 = 30_000;
/// 单个文件事件的去抖说明。
///
/// worker 是「来一条处理一条」,去抖由三层共同承担:notify 自身的派发合并、
/// 前端 `editor-library-changed` 的 400ms 防抖、以及自我保存抑制窗口。
/// 之所以不在这里再加一个定时器:多一层延迟就多一个「事件丢了谁负责」的疑问,
/// 而下游每一层都是幂等的(重复同步同一个文件只是重算一次 hash)。
const _DEBOUNCE_NOTE_MS: u64 = 250;
/// 库文件变化的分类(前端据此决定「重载当前笔记」还是「只刷新树」)。
///
/// 只有 `removed` 是确定事实(文件不在了);「新建」与「修改」在单文件事件层面
/// **无法区分**(notify 给的 `Create` 与 `Modify` 在一次保存里会同时出现),
/// 因此统一报 [`CHANGE_MODIFIED`],由前端按「路径在不在当前树里」自行判断。
pub const CHANGE_MODIFIED: &str = "modified";
pub const CHANGE_REMOVED: &str = "removed";
/// 广播给各窗口的库文件变化事件。
#[derive(Debug, Clone, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct NoteFileEvent {
/// 相对库根的路径(`/` 分隔)
pub rel_path: String,
/// 磁盘上的绝对路径。
///
/// 前端需要它来判断「这个事件说的是不是我正在编辑的那个库外文件」——
/// 相对库根路径对库外文件没有意义(它根本不在库里),只留 `rel_path`
/// 会让「打开 D:\x\a.md 时有人在别处改了它」永远匹配不上。
pub abs_path: String,
/// "modified" | "removed"
pub kind: String,
/// 事件发生时间(Unix 毫秒)
pub at: u64,
/// 是否是本应用自己写入造成的(前端据此跳过「外部修改」提示)
pub from_app: bool,
}
/// 一次索引同步的结果(命令返回值)。
#[derive(Debug, Clone, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct NoteIndexReport {
pub indexed: i64,
pub removed: i64,
pub skipped: i64,
/// 同步后索引里的笔记数(前端直接显示,省一次统计往返)
pub note_count: i64,
}
impl From<NoteSyncReport> for NoteIndexReport {
fn from(report: NoteSyncReport) -> Self {
Self {
indexed: report.indexed,
removed: report.removed,
skipped: report.skipped,
note_count: 0,
}
}
}
/// worker 请求。
enum Request {
/// 增量同步整个库
Sync(Sender<Result<NoteSyncReport, String>>),
/// 全量重建
Rebuild(Sender<Result<NoteSyncReport, String>>),
/// 同步单个文件(监听器投递;文件不存在则从索引移除)
SyncPath(PathBuf),
/// 全文检索
Search(NoteSearchQuery, Sender<Result<NoteSearchPage, String>>),
/// 快速打开清单
List(i64, Sender<Result<Vec<NoteSearchHit>, String>>),
/// 标签清单
Tags(Sender<Result<Vec<super::index::NoteTagCount>, String>>),
/// 一篇笔记的出链 / 入链
Backlinks(String, Sender<Result<super::index::NoteBacklinks, String>>),
/// 全库链接图
LinkGraph(Sender<Result<Vec<(String, String)>, String>>),
/// 索引状态
Stats(Sender<Result<NoteIndexStats, String>>),
/// 重建监听器(库根变化后)
Retarget(PathBuf, Sender<Result<(), String>>),
}
/// 一条「本应用自己写入」的登记。
struct SelfWrite {
/// 库内相对路径(`/` 分隔,与 [`library::rel_string`] 的输出一致)
rel: String,
/// 登记时刻(写入之前,见 [`IndexService::mark_write_path`])
marked: Instant,
/// 首次被文件事件命中的时刻(`None` = 还没等到它的事件)
matched: Option<Instant>,
}
/// 丢弃过期的自我写入登记。
///
/// - **已命中**:保留 [`SUPPRESS_MS`] —— 覆盖同一次写入产生的重复事件。
/// - **未命中**:保留 [`SELF_WRITE_TTL_MS`] —— 等它的文件事件到达(notify 延迟可能到秒级)。
fn prune_self_writes(paths: &mut Vec<SelfWrite>) {
let dedupe = Duration::from_millis(SUPPRESS_MS);
let wait = Duration::from_millis(SELF_WRITE_TTL_MS);
paths.retain(|entry| match entry.matched {
Some(at) => at.elapsed() < dedupe,
None => entry.marked.elapsed() < wait,
});
}
/// 索引服务的句柄(命令层只拿到这个)。
pub struct IndexService {
tx: Sender<Request>,
/// 批量自我写入的时间点(导入 / WebDAV 同步 / 恢复 / 模板导出这类无法逐路径枚举的操作)。
/// 窗口内的一切文件事件都当作「自己写的」,不向前端提示外部修改。
bulk_write: Mutex<Option<Instant>>,
/// 单个文件的自我写入登记。
/// 比批量窗口精确:保存 A 不会再顺带吞掉 B 的外部改动事件。
write_paths: Mutex<Vec<SelfWrite>>,
}
static SERVICE: std::sync::OnceLock<IndexService> = std::sync::OnceLock::new();
/// 取索引服务(首次调用时启动 worker 线程与监听器)。
pub fn service(app: &AppHandle) -> &'static IndexService {
SERVICE.get_or_init(|| IndexService::start(app.clone()))
}
impl IndexService {
fn start(app: AppHandle) -> Self {
let (tx, rx) = mpsc::channel::<Request>();
let handle_tx = tx.clone();
std::thread::Builder::new()
.name("editor-index".to_string())
.spawn(move || worker_loop(app, rx, handle_tx))
.expect("启动笔记索引线程失败");
Self {
tx,
bulk_write: Mutex::new(None),
write_paths: Mutex::new(Vec::new()),
}
}
/// 标记「刚刚由本应用**批量**写入了文件」(导入 / 同步 / 恢复 / 模板导出)。
/// 这类操作无法逐路径枚举,窗口内一律视为自我写入。
pub fn mark_write_all(&self) {
if let Ok(mut slot) = self.bulk_write.lock() {
*slot = Some(Instant::now());
}
}
/// 登记「本应用即将写入这个库内相对路径」。
///
/// **必须在真正的 `fs::write` 之前调用**:notify 的 Modify 事件可能与写入几乎同时
/// 到达 worker,若等写盘回来再登记,事件可能已经被处理并误判为「外部修改」。
pub fn mark_write_path(&self, rel: &str) {
if rel.is_empty() {
return;
}
if let Ok(mut paths) = self.write_paths.lock() {
prune_self_writes(&mut paths);
paths.push(SelfWrite {
rel: rel.to_string(),
marked: Instant::now(),
matched: None,
});
}
}
/// 这个库内相对路径是不是「本应用自己刚写的」。
///
/// 命中**一次就算消费**:优先匹配还没命中过的登记(一次写入对应一次命中),
/// 找不到才回退到刚命中过的(覆盖同一次写入的重复事件)。这样即便 notify 延迟到
/// 秒级,登记项仍在(见 [`SELF_WRITE_TTL_MS`]),不会把自家的保存误判成外部修改。
fn recently_written(&self, rel: &str) -> bool {
let bulk = self
.bulk_write
.lock()
.ok()
.and_then(|slot| *slot)
.map(|at| at.elapsed() < Duration::from_millis(SUPPRESS_MS))
.unwrap_or(false);
if bulk {
return true;
}
let Ok(mut paths) = self.write_paths.lock() else {
return false;
};
prune_self_writes(&mut paths);
let index = paths
.iter()
.position(|entry| entry.rel == rel && entry.matched.is_none())
.or_else(|| paths.iter().position(|entry| entry.rel == rel));
let Some(index) = index else {
return false;
};
let entry = &mut paths[index];
entry.matched.get_or_insert_with(Instant::now);
true
}
/// 增量同步整个库。
pub fn sync(&self) -> Result<NoteSyncReport, String> {
let (tx, rx) = mpsc::channel();
self.tx
.send(Request::Sync(tx))
.map_err(|_| "索引服务已停止".to_string())?;
rx.recv().map_err(|_| "索引服务无响应".to_string())?
}
/// 全量重建索引。
pub fn rebuild(&self) -> Result<NoteSyncReport, String> {
let (tx, rx) = mpsc::channel();
self.tx
.send(Request::Rebuild(tx))
.map_err(|_| "索引服务已停止".to_string())?;
rx.recv().map_err(|_| "索引服务无响应".to_string())?
}
/// 全文检索。
pub fn search(&self, query: NoteSearchQuery) -> Result<NoteSearchPage, String> {
let (tx, rx) = mpsc::channel();
self.tx
.send(Request::Search(query, tx))
.map_err(|_| "索引服务已停止".to_string())?;
rx.recv().map_err(|_| "索引服务无响应".to_string())?
}
/// 快速打开清单。
pub fn list(&self, limit: i64) -> Result<Vec<NoteSearchHit>, String> {
let (tx, rx) = mpsc::channel();
self.tx
.send(Request::List(limit, tx))
.map_err(|_| "索引服务已停止".to_string())?;
rx.recv().map_err(|_| "索引服务无响应".to_string())?
}
/// 标签清单。
pub fn tags(&self) -> Result<Vec<super::index::NoteTagCount>, String> {
let (tx, rx) = mpsc::channel();
self.tx
.send(Request::Tags(tx))
.map_err(|_| "索引服务已停止".to_string())?;
rx.recv().map_err(|_| "索引服务无响应".to_string())?
}
/// 索引状态。
pub fn stats(&self) -> Result<NoteIndexStats, String> {
let (tx, rx) = mpsc::channel();
self.tx
.send(Request::Stats(tx))
.map_err(|_| "索引服务已停止".to_string())?;
rx.recv().map_err(|_| "索引服务无响应".to_string())?
}
/// 一篇笔记的出链 / 入链。
pub fn backlinks(&self, rel_path: &str) -> Result<super::index::NoteBacklinks, String> {
let (tx, rx) = mpsc::channel();
self.tx
.send(Request::Backlinks(rel_path.to_string(), tx))
.map_err(|_| "索引服务已停止".to_string())?;
rx.recv().map_err(|_| "索引服务无响应".to_string())?
}
/// 全库链接图(已解析的内部链接边)。
pub fn link_graph(&self) -> Result<Vec<(String, String)>, String> {
let (tx, rx) = mpsc::channel();
self.tx
.send(Request::LinkGraph(tx))
.map_err(|_| "索引服务已停止".to_string())?;
rx.recv().map_err(|_| "索引服务无响应".to_string())?
}
/// 切换库根(重新打开索引 + 重建监听器)。
pub fn retarget(&self, root: PathBuf) -> Result<(), String> {
let (tx, rx) = mpsc::channel();
self.tx
.send(Request::Retarget(root, tx))
.map_err(|_| "索引服务已停止".to_string())?;
rx.recv().map_err(|_| "索引服务无响应".to_string())?
}
}
/// worker 主循环:独占 [`EditorIndex`],串行处理所有请求。
fn worker_loop(app: AppHandle, rx: Receiver<Request>, handle_tx: Sender<Request>) {
let mut index: Option<EditorIndex> = None;
let mut watcher: Option<RecommendedWatcher> = None;
let mut watched_root: Option<PathBuf> = None;
let mut root: Option<PathBuf> = None;
while let Ok(request) = rx.recv() {
match request {
Request::Sync(reply) => {
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.sync()));
}
Request::Rebuild(reply) => {
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.rebuild()));
}
Request::Search(query, reply) => {
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.search(query)));
}
Request::List(limit, reply) => {
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.list_notes(limit)));
}
Request::Tags(reply) => {
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.tags()));
}
Request::Backlinks(rel_path, reply) => {
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| {
idx.backlinks(&rel_path)
}));
}
Request::LinkGraph(reply) => {
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.link_graph()));
}
Request::Stats(reply) => {
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.stats()));
}
Request::Retarget(next, reply) => {
// 库根未变:直接返回,不重开索引、不重建监听器。
// 早期实现每次都 `index = None` + 重挂 watcher,于是**每次自动保存**都要重开
// SQLite 连接、重建 notify 监听,既慢,又让「写入 → 事件」挤进这段重建窗口,
// 制造出「自己保存却被当成外部修改」的竞态。
if root.as_deref() == Some(next.as_path()) {
let _ = reply.send(Ok(()));
continue;
}
// 库根切换:丢掉旧索引实例,下次操作按新库根重新打开
index = None;
root = Some(next.clone());
let result = match ensure_index(&app, &mut index, &next) {
Ok(_) => {
watched_root = None; // 触发重建监听器
Ok(())
}
Err(e) => Err(e),
};
let _ = reply.send(result);
// 新库的监听器要在回复之后建:先让前端拿到「已切换」的结果
ensure_watcher(&mut watcher, &mut watched_root, &next, &handle_tx);
}
Request::SyncPath(path) => {
if let Some(current) = root.clone() {
// 索引尚未建立时先建(首次操作前就被外部改动的情况)
if index.is_none() {
if let Err(e) = ensure_index(&app, &mut index, &current) {
crate::logger::log_warn("editor", &format!("索引不可用: {e}"));
continue;
}
}
ensure_watcher(&mut watcher, &mut watched_root, &current, &handle_tx);
sync_one(&app, index.as_mut(), &current, &path);
}
}
}
}
}
/// 借出索引(必要时按 `root` 打开),并把结果映射成 `Result<_, String>`。
fn with_index<T>(
app: &AppHandle,
index: &mut Option<EditorIndex>,
root: &mut Option<PathBuf>,
run: impl FnOnce(&mut EditorIndex) -> Result<T, String>,
) -> Result<T, String> {
let Some(current) = root.clone() else {
// 不在这里猜库根:命令层每次操作前都会 `retarget` 到当前库根,
// 猜错的后果是索引挂到别的目录上(用户切过库时尤其明显)。
return Err("索引尚未指向任何笔记库(请先打开笔记窗口)".to_string());
};
ensure_index(app, index, &current)?;
match index.as_mut() {
Some(idx) => run(idx),
None => Err("索引未就绪".to_string()),
}
}
/// 确保索引实例存在且指向 `root`(不匹配则重新打开)。
fn ensure_index(app: &AppHandle, index: &mut Option<EditorIndex>, root: &Path) -> Result<(), String> {
if let Some(existing) = index.as_ref() {
if existing.root() == root {
return Ok(());
}
}
if let Err(e) = library::ensure_library(root) {
crate::logger::log_warn("editor", &e);
}
let opened = EditorIndex::open(root)?;
crate::logger::log_info(
"editor",
&format!("索引已就绪: {}", opened.db_path().display()),
);
// 首次打开时不自动全量同步:库可能很大,交给命令层(打开编辑器 / 重建索引时)触发
let _ = app;
*index = Some(opened);
Ok(())
}
/// 确保监听器挂在 `root` 上。
fn ensure_watcher(
watcher: &mut Option<RecommendedWatcher>,
watched_root: &mut Option<PathBuf>,
root: &Path,
tx: &Sender<Request>,
) {
if let Err(e) = ensure_watcher_inner(watcher, watched_root, root, tx) {
crate::logger::log_warn("editor", &e);
}
}
/// 建/换监听器(`root` 未变则不动)。
fn ensure_watcher_inner(
watcher: &mut Option<RecommendedWatcher>,
watched_root: &mut Option<PathBuf>,
root: &Path,
tx: &Sender<Request>,
) -> Result<(), String> {
if watched_root.as_deref() == Some(root) && watcher.is_some() {
return Ok(());
}
let sender = tx.clone();
let mut next = notify::recommended_watcher(move |event: notify::Result<notify::Event>| {
let Ok(event) = event else { return };
for path in event_paths(&event) {
let _ = sender.send(Request::SyncPath(path));
}
})
.map_err(|e| format!("创建库监听器失败: {e}"))?;
next.watch(root, RecursiveMode::Recursive)
.map_err(|e| format!("监听笔记库失败: {e}"))?;
// 替换旧监听器(drop 即 unwatch)
*watcher = Some(next);
*watched_root = Some(root.to_path_buf());
crate::logger::log_info("editor", &format!("库监听已启动: {}", root.display()));
Ok(())
}
/// 从 notify 事件里取出「值得同步」的路径(只关心 .md,且忽略 `.editor/` 自身)。
///
/// 重命名会给出两个路径(旧、新),这里都收下:旧路径在同步时会发现「文件不存在」
/// 而被当作删除处理,新路径自然成为新增 —— 无需专门分辨 RenameMode。
fn event_paths(event: &notify::Event) -> Vec<PathBuf> {
if matches!(event.kind, EventKind::Access(_) | EventKind::Other) {
return Vec::new();
}
event
.paths
.iter()
.filter(|p| {
let name = p.file_name().map(|n| n.to_string_lossy().to_string());
// 只跟踪 .md 与目录事件(目录事件用于捕捉「整目录移入」)
let is_md = name
.as_deref()
.map(|n| n.to_ascii_lowercase().ends_with(".md"))
.unwrap_or(false);
let is_meta = p
.components()
.any(|c| c.as_os_str().to_string_lossy().starts_with('.'));
is_md && !is_meta
})
.cloned()
.collect()
}
/// 就地同步单个文件(含自我保存抑制与前端事件广播)。
///
/// 事件是否「本应用自己写的」按**库内相对路径**判定(见 [`IndexService::mark_write_path`]),
/// 而不是一个全局时间窗 —— 全局窗会把「保存 A 之后 1.2s 内 B 被外部改动」也一并吞掉。
fn sync_one(app: &AppHandle, index: Option<&mut EditorIndex>, root: &Path, path: &Path) {
let Some(index) = index else { return };
let rel = library::rel_string(root, path);
if rel.is_empty() || rel.starts_with('.') || rel.starts_with("assets/") {
return;
}
// 自我保存抑制:只影响「是否提示用户」,索引照常更新
let self_write = SERVICE
.get()
.map(|service| service.recently_written(&rel))
.unwrap_or(false);
let kind = if path.is_file() {
if let Ok(bytes) = std::fs::read(path) {
let content = String::from_utf8_lossy(&bytes);
let meta = std::fs::metadata(path).ok();
let mtime = meta
.as_ref()
.and_then(|m| m.modified().ok())
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_millis() as u64)
.unwrap_or(0);
let stems = std::collections::HashMap::new();
if let Err(e) = index.upsert_note(
&rel,
&content,
mtime,
meta.as_ref().map(|m| m.len()).unwrap_or(0),
&content_hash(&bytes),
&stems,
) {
crate::logger::log_warn("editor", &format!("增量索引 {rel} 失败: {e}"));
}
} else {
return;
}
// 无法分辨「新建」与「修改」时统一报 modified:前端对两者的处理相同
// (重载树)。真正需要区分时以库扫描结果为准。
CHANGE_MODIFIED
} else {
if let Err(e) = index.remove_note(&rel) {
crate::logger::log_warn("editor", &format!("移除索引 {rel} 失败: {e}"));
}
CHANGE_REMOVED
};
// 事件一律发出,用 `from_app` 如实标注来源,由前端决定是否提示/重载。
// 早期实现是「自己写的就静默不发」,一旦自我写入判定因时序漏过,前端就会把自家
// 的保存当成外部修改而重载文档(光标弹回第一行)—— 判定留在前端更稳。
let payload = NoteFileEvent {
rel_path: rel,
abs_path: files::display_path(path),
kind: kind.to_string(),
at: std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0),
from_app: self_write,
};
if let Err(e) = app.emit(events::EDITOR_FILE_CHANGED, payload) {
crate::logger::log_warn("editor", &format!("发出文件变化事件失败: {e}"));
}
}
/// 授权 + 读取(供命令层调用,收敛「读文件必须先登记授权」这条规则)。
pub fn read_and_authorize(path: &str, max_mb: u32) -> Result<files::FileDoc, String> {
let doc = files::read_file(path, max_mb)?;
files::authorize(Path::new(&doc.path));
Ok(doc)
}