package app import ( "fmt" "os" "path/filepath" "sync" ) // lockDatabaseInstance acquires a non-blocking OS kernel lock for dbPath before // startup recovery mutates SQLite tables (such as hitl_interrupts, messages, // mcp_executions, or deep_assessments). If a second server process is started // accidentally while the primary server is still bound and running tasks, the // second process fails fast without corrupting the live server's task state. func lockDatabaseInstance(dbPath string) (func(), error) { absPath, err := filepath.Abs(dbPath) if err != nil { return nil, err } if err := os.MkdirAll(filepath.Dir(absPath), 0755); err != nil { return nil, fmt.Errorf("创建数据库目录失败: %w", err) } lockPath := absPath + ".instance.lock" f, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0600) if err != nil { return nil, fmt.Errorf("打开实例锁文件失败 (%s): %w", lockPath, err) } if err := tryLockInstanceFile(f); err != nil { _ = f.Close() return nil, fmt.Errorf("另一个 CyberStrikeAI 服务实例正在运行并占用数据库 %s(请先停止旧进程,或在系统设置中使用一键更新)", dbPath) } var once sync.Once return func() { once.Do(func() { _ = f.Close() }) }, nil }