An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: Automatically perform index fixing during idle time https://github.com/siyuan-note/siyuan/issues/17535
Daniel0515b6e94bfd
diff --git a/kernel/job/cron.go b/kernel/job/cron.goindex 7a00475e16..016e6b3879 100644--- a/kernel/job/cron.go+++ b/kernel/job/cron.go@@ -45,6 +45,7 @@ func StartCron() {go every(30*time.Second, model.FlushAssetsTextsJob)go every(30*time.Second, model.HookDesktopUIProcJob)go every(24*time.Hour, model.AutoPurgeRepoJob)+ go every(1*time.Minute, model.AutoFixIndex, "AutoFixIndex")go every(30*time.Minute, model.AutoCheckMicrosoftDefenderJob)go every(24*time.Hour, model.ClearOutdatedHistoryDirJob)if util.IsMobileContainer() {diff --git a/kernel/model/index_fix.go b/kernel/model/index_fix.goindex b0e2e9d1cc..94e7e9c142 100644--- a/kernel/model/index_fix.go+++ b/kernel/model/index_fix.go@@ -43,6 +43,18 @@ import (var (checkIndexOnce = sync.Once{}++ // fixIndexMu 保证 checkIndex 与 AutoFixIndex 互斥,不会并发跑同一套订正。+ fixIndexMu sync.Mutex+ // lastFixedAt 记录上次订正完成时间,用于 AutoFixIndex 的冷却期判断。+ lastFixedAt time.Time+)++const (+ // idleFixThreshold 为用户空闲超过该阈值后才允许触发空闲订正。+ idleFixThreshold = 7 * time.Minute+ // fixCooldown 为上次订正后至少间隔该时长才允许下一次空闲订正。+ fixCooldown = 120 * time.Minute)// checkIndex 自动校验数据库索引,仅在数据同步执行完成后执行一次。@@ -54,28 +66,73 @@ func checkIndex() {return}- logging.LogInfof("start checking index...")+ // 阻塞式获取锁:若 AutoFixIndex 正在跑则等其完成,确保唯一一次校验不会与之并发+ fixIndexMu.Lock()+ defer fixIndexMu.Unlock()- removeDuplicateDatabaseIndex()- sql.FlushQueue()+ fixIndexPipeline()+ })+}- resetDuplicateBlocksOnFileSys()- sql.FlushQueue()+// fixIndexPipeline 执行索引订正流水线。+// 由 checkIndex(同步后一次性)与 AutoFixIndex(空闲触发)共用,调用方负责加 fixIndexMu 互斥锁。+func fixIndexPipeline() {+ logging.LogInfof("start fixing index...")- fixBlockTreeByFileSys()- sql.FlushQueue()+ removeDuplicateDatabaseIndex()+ sql.FlushQueue()- fixDatabaseIndexByBlockTree()- sql.FlushQueue()+ resetDuplicateBlocksOnFileSys()+ sql.FlushQueue()- removeDuplicateDatabaseRefs()+ fixBlockTreeByFileSys()+ sql.FlushQueue()- // 后面要加任务的话记得修改推送任务栏的进度 util.PushStatusBar(fmt.Sprintf(Conf.Language(58), 1, 5))+ fixDatabaseIndexByBlockTree()+ sql.FlushQueue()- debug.FreeOSMemory()- util.PushStatusBar(Conf.Language(185))- logging.LogInfof("finish checking index")- })+ removeDuplicateDatabaseRefs()++ // 后面要加任务的话记得修改推送任务栏的进度 util.PushStatusBar(fmt.Sprintf(Conf.Language(58), 1, 5))++ debug.FreeOSMemory()+ util.PushStatusBar(Conf.Language(185))+ logging.LogInfof("finish fixing index")+}++// AutoFixIndex 在用户空闲且存在未订正变更时,自动订正索引。由 cron 每分钟调用。+// 触发需同时满足:空闲达 idleFixThreshold、存在未订正变更(dirty)、冷却期已过。+func AutoFixIndex() {+ defer logging.Recover()++ if util.IsMobileContainer() {+ return+ }+ if !util.IsIdle(idleFixThreshold) {+ return+ }+ if !util.IsIndexFixDirty() {+ return+ }+ if !lastFixedAt.IsZero() && time.Since(lastFixedAt) < fixCooldown {+ return+ }+ // TryLock 非阻塞:若 checkIndex 正在跑或上次还没跑完,直接跳过,不堆积 goroutine+ if !fixIndexMu.TryLock() {+ return+ }+ defer fixIndexMu.Unlock()++ // double-check:拿到锁后再确认一次确实空闲,避免在等待锁期间用户又开始操作+ if !util.IsIdle(idleFixThreshold) {+ return+ }++ logging.LogInfof("start auto fixing index on idle...")+ fixIndexPipeline()+ util.MarkIndexClean()+ lastFixedAt = time.Now()+ logging.LogInfof("finish auto fixing index on idle")}// removeDuplicateDatabaseRefs 删除重复的数据库引用关系。diff --git a/kernel/server/serve.go b/kernel/server/serve.goindex fa981d27ac..7a44bce1e3 100644--- a/kernel/server/serve.go+++ b/kernel/server/serve.go@@ -867,6 +867,7 @@ func serveWebSocket(ginServer *gin.Engine) {util.WebSocketServer.HandleMessage(func(s *melody.Session, msg []byte) {start := time.Now()+ util.RefreshActivity()logging.LogTracef("request [%s]", shortReqMsg(msg))if util.IsAuthSession(s) {diff --git a/kernel/util/websocket.go b/kernel/util/websocket.goindex 238ca092d6..ac78ea31d3 100644--- a/kernel/util/websocket.go+++ b/kernel/util/websocket.go@@ -19,6 +19,7 @@ package utilimport ("strings""sync"+ "sync/atomic""time""github.com/88250/gulu"@@ -548,3 +549,37 @@ func ClosePublishServiceSessions() {RemovePushChan(session)}}++var (+ // lastActivityNs 记录最近一次用户活动(前端发送 WebSocket cmd)的纳秒时间戳。+ lastActivityNs atomic.Int64+ // indexFixDirty 标记索引可能已脏(上次订正后用户又有新活动),需要再次订正。+ indexFixDirty atomic.Bool+)++func init() {+ // 初始化为启动时间,避免启动瞬间被判定为空闲+ lastActivityNs.Store(time.Now().UnixNano())+}++// RefreshActivity 刷新用户最近活动时间,并标记索引可能已脏(需要订正)。+// 在 server.HandleMessage 收到前端任何 cmd 时调用。+func RefreshActivity() {+ lastActivityNs.Store(time.Now().UnixNano())+ indexFixDirty.Store(true)+}++// MarkIndexClean 标记索引已订正完成,清除脏标志。订正流水线结束后调用。+func MarkIndexClean() {+ indexFixDirty.Store(false)+}++// IsIdle 自上次用户活动以来是否已超过 idleThreshold。+func IsIdle(idleThreshold time.Duration) bool {+ return time.Since(time.Unix(0, lastActivityNs.Load())) >= idleThreshold+}++// IsIndexFixDirty 返回是否存在未订正的变更(上次订正后有新用户活动)。+func IsIndexFixDirty() bool {+ return indexFixDirty.Load()+}