queue.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. // SiYuan - Build Your Eternal Digital Garden
  2. // Copyright (c) 2020-present, b3log.org
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. package sql
  17. import (
  18. "database/sql"
  19. "errors"
  20. "fmt"
  21. "path"
  22. "runtime/debug"
  23. "sync"
  24. "time"
  25. "github.com/88250/lute/parse"
  26. "github.com/siyuan-note/eventbus"
  27. "github.com/siyuan-note/logging"
  28. "github.com/siyuan-note/siyuan/kernel/av"
  29. "github.com/siyuan-note/siyuan/kernel/task"
  30. "github.com/siyuan-note/siyuan/kernel/util"
  31. )
  32. var (
  33. operationQueue []*dbQueueOperation
  34. dbQueueLock = sync.Mutex{}
  35. txLock = sync.Mutex{}
  36. )
  37. type dbQueueOperation struct {
  38. inQueueTime time.Time
  39. action string // upsert/delete/delete_id/rename/rename_sub_tree/delete_box/delete_box_refs/insert_refs/index/delete_ids/update_block_content/delete_assets/av_rebuild
  40. indexPath string // index
  41. upsertTree *parse.Tree // upsert/insert_refs/update_refs/delete_refs
  42. removeTreeBox, removeTreePath string // delete
  43. removeTreeIDBox, removeTreeID string // delete_id
  44. removeTreeIDs []string // delete_ids
  45. box string // delete_box/delete_box_refs/index
  46. renameTree *parse.Tree // rename/rename_sub_tree
  47. block *Block // update_block_content
  48. removeAssetHashes []string // delete_assets
  49. av *av.AttributeView // av_rebuild
  50. }
  51. func FlushTxJob() {
  52. task.AppendTask(task.DatabaseIndexCommit, FlushQueue)
  53. }
  54. func WaitForWritingDatabase() {
  55. var printLog bool
  56. var lastPrintLog bool
  57. for i := 0; isWritingDatabase(); i++ {
  58. time.Sleep(50 * time.Millisecond)
  59. if 200 < i && !printLog { // 10s 后打日志
  60. logging.LogWarnf("database is writing: \n%s", logging.ShortStack())
  61. printLog = true
  62. }
  63. if 1200 < i && !lastPrintLog { // 60s 后打日志
  64. logging.LogWarnf("database is still writing")
  65. lastPrintLog = true
  66. }
  67. }
  68. }
  69. func isWritingDatabase() bool {
  70. time.Sleep(util.SQLFlushInterval + 50*time.Millisecond)
  71. if 0 < len(operationQueue) || util.IsMutexLocked(&txLock) {
  72. return true
  73. }
  74. return false
  75. }
  76. func IsEmptyQueue() bool {
  77. return 1 > len(operationQueue) && !util.IsMutexLocked(&txLock)
  78. }
  79. func ClearQueue() {
  80. dbQueueLock.Lock()
  81. defer dbQueueLock.Unlock()
  82. operationQueue = nil
  83. }
  84. func FlushQueue() {
  85. ops := mergeUpsertTrees()
  86. if 1 > len(ops) {
  87. return
  88. }
  89. txLock.Lock()
  90. defer txLock.Unlock()
  91. start := time.Now()
  92. context := map[string]interface{}{eventbus.CtxPushMsg: eventbus.CtxPushMsgToStatusBar}
  93. total := len(ops)
  94. if 512 < total {
  95. disableCache()
  96. defer enableCache()
  97. }
  98. groupOpsTotal := map[string]int{}
  99. for _, op := range ops {
  100. groupOpsTotal[op.action]++
  101. }
  102. groupOpsCurrent := map[string]int{}
  103. for i, op := range ops {
  104. if util.IsExiting {
  105. return
  106. }
  107. tx, err := beginTx()
  108. if nil != err {
  109. return
  110. }
  111. groupOpsCurrent[op.action]++
  112. context["current"] = groupOpsCurrent[op.action]
  113. context["total"] = groupOpsTotal[op.action]
  114. if err = execOp(op, tx, context); nil != err {
  115. tx.Rollback()
  116. logging.LogErrorf("queue operation [%s] failed: %s", op.action, err)
  117. continue
  118. }
  119. if err = commitTx(tx); nil != err {
  120. logging.LogErrorf("commit tx failed: %s", err)
  121. return
  122. }
  123. if 16 < i && 0 == i%128 {
  124. debug.FreeOSMemory()
  125. }
  126. }
  127. if 128 < len(ops) {
  128. debug.FreeOSMemory()
  129. }
  130. elapsed := time.Now().Sub(start).Milliseconds()
  131. if 7000 < elapsed {
  132. logging.LogInfof("database op tx [%dms]", elapsed)
  133. }
  134. }
  135. func execOp(op *dbQueueOperation, tx *sql.Tx, context map[string]interface{}) (err error) {
  136. switch op.action {
  137. case "index":
  138. err = indexTree(tx, op.box, op.indexPath, context)
  139. case "upsert":
  140. err = upsertTree(tx, op.upsertTree, context)
  141. case "delete":
  142. err = batchDeleteByPathPrefix(tx, op.removeTreeBox, op.removeTreePath)
  143. case "delete_id":
  144. err = deleteByRootID(tx, op.removeTreeID, context)
  145. case "delete_ids":
  146. err = batchDeleteByRootIDs(tx, op.removeTreeIDs, context)
  147. case "rename":
  148. err = batchUpdateHPath(tx, op.renameTree.Box, op.renameTree.ID, op.renameTree.HPath, context)
  149. if nil != err {
  150. break
  151. }
  152. err = updateRootContent(tx, path.Base(op.renameTree.HPath), op.renameTree.Root.IALAttr("updated"), op.renameTree.ID)
  153. case "rename_sub_tree":
  154. err = batchUpdateHPath(tx, op.renameTree.Box, op.renameTree.ID, op.renameTree.HPath, context)
  155. case "delete_box":
  156. err = deleteByBoxTx(tx, op.box)
  157. case "delete_box_refs":
  158. err = deleteRefsByBoxTx(tx, op.box)
  159. case "insert_refs":
  160. err = insertRefs(tx, op.upsertTree)
  161. case "update_refs":
  162. err = upsertRefs(tx, op.upsertTree)
  163. case "delete_refs":
  164. err = deleteRefs(tx, op.upsertTree)
  165. case "update_block_content":
  166. err = updateBlockContent(tx, op.block)
  167. case "delete_assets":
  168. err = deleteAssetsByHashes(tx, op.removeAssetHashes)
  169. case "av_rebuild":
  170. err = av.RebuildAttributeViewTable(tx, op.av)
  171. default:
  172. msg := fmt.Sprintf("unknown operation [%s]", op.action)
  173. logging.LogErrorf(msg)
  174. err = errors.New(msg)
  175. }
  176. return
  177. }
  178. func RebuildAttributeViewQueue(av *av.AttributeView) {
  179. dbQueueLock.Lock()
  180. defer dbQueueLock.Unlock()
  181. newOp := &dbQueueOperation{av: av, inQueueTime: time.Now(), action: "av_rebuild"}
  182. for i, op := range operationQueue {
  183. if "av_rebuild" == op.action && op.av.ID == av.ID {
  184. operationQueue[i] = newOp
  185. return
  186. }
  187. }
  188. operationQueue = append(operationQueue, newOp)
  189. }
  190. func BatchRemoveAssetsQueue(hashes []string) {
  191. if 1 > len(hashes) {
  192. return
  193. }
  194. dbQueueLock.Lock()
  195. defer dbQueueLock.Unlock()
  196. newOp := &dbQueueOperation{removeAssetHashes: hashes, inQueueTime: time.Now(), action: "delete_assets"}
  197. operationQueue = append(operationQueue, newOp)
  198. }
  199. func UpdateBlockContentQueue(block *Block) {
  200. dbQueueLock.Lock()
  201. defer dbQueueLock.Unlock()
  202. newOp := &dbQueueOperation{block: block, inQueueTime: time.Now(), action: "update_block_content"}
  203. for i, op := range operationQueue {
  204. if "update_block_content" == op.action && op.block.ID == block.ID {
  205. operationQueue[i] = newOp
  206. return
  207. }
  208. }
  209. operationQueue = append(operationQueue, newOp)
  210. }
  211. func DeleteRefsTreeQueue(tree *parse.Tree) {
  212. dbQueueLock.Lock()
  213. defer dbQueueLock.Unlock()
  214. newOp := &dbQueueOperation{upsertTree: tree, inQueueTime: time.Now(), action: "delete_refs"}
  215. for i, op := range operationQueue {
  216. if "delete_refs" == op.action && op.upsertTree.ID == tree.ID {
  217. operationQueue[i] = newOp
  218. return
  219. }
  220. }
  221. operationQueue = append(operationQueue, newOp)
  222. }
  223. func UpdateRefsTreeQueue(tree *parse.Tree) {
  224. dbQueueLock.Lock()
  225. defer dbQueueLock.Unlock()
  226. newOp := &dbQueueOperation{upsertTree: tree, inQueueTime: time.Now(), action: "update_refs"}
  227. for i, op := range operationQueue {
  228. if "update_refs" == op.action && op.upsertTree.ID == tree.ID {
  229. operationQueue[i] = newOp
  230. return
  231. }
  232. }
  233. operationQueue = append(operationQueue, newOp)
  234. }
  235. func InsertRefsTreeQueue(tree *parse.Tree) {
  236. dbQueueLock.Lock()
  237. defer dbQueueLock.Unlock()
  238. newOp := &dbQueueOperation{upsertTree: tree, inQueueTime: time.Now(), action: "insert_refs"}
  239. for i, op := range operationQueue {
  240. if "insert_refs" == op.action && op.upsertTree.ID == tree.ID {
  241. operationQueue[i] = newOp
  242. return
  243. }
  244. }
  245. operationQueue = append(operationQueue, newOp)
  246. }
  247. func DeleteBoxRefsQueue(boxID string) {
  248. dbQueueLock.Lock()
  249. defer dbQueueLock.Unlock()
  250. newOp := &dbQueueOperation{box: boxID, inQueueTime: time.Now(), action: "delete_box_refs"}
  251. for i, op := range operationQueue {
  252. if "delete_box_refs" == op.action && op.box == boxID {
  253. operationQueue[i] = newOp
  254. return
  255. }
  256. }
  257. operationQueue = append(operationQueue, newOp)
  258. }
  259. func DeleteBoxQueue(boxID string) {
  260. dbQueueLock.Lock()
  261. defer dbQueueLock.Unlock()
  262. newOp := &dbQueueOperation{box: boxID, inQueueTime: time.Now(), action: "delete_box"}
  263. for i, op := range operationQueue {
  264. if "delete_box" == op.action && op.box == boxID {
  265. operationQueue[i] = newOp
  266. return
  267. }
  268. }
  269. operationQueue = append(operationQueue, newOp)
  270. }
  271. func IndexTreeQueue(box, p string) {
  272. dbQueueLock.Lock()
  273. defer dbQueueLock.Unlock()
  274. newOp := &dbQueueOperation{indexPath: p, box: box, inQueueTime: time.Now(), action: "index"}
  275. for i, op := range operationQueue {
  276. if "index" == op.action && op.indexPath == p && op.box == box { // 相同树则覆盖
  277. operationQueue[i] = newOp
  278. return
  279. }
  280. }
  281. operationQueue = append(operationQueue, newOp)
  282. }
  283. func UpsertTreeQueue(tree *parse.Tree) {
  284. dbQueueLock.Lock()
  285. defer dbQueueLock.Unlock()
  286. newOp := &dbQueueOperation{upsertTree: tree, inQueueTime: time.Now(), action: "upsert"}
  287. for i, op := range operationQueue {
  288. if "upsert" == op.action && op.upsertTree.ID == tree.ID { // 相同树则覆盖
  289. operationQueue[i] = newOp
  290. return
  291. }
  292. }
  293. operationQueue = append(operationQueue, newOp)
  294. }
  295. func RenameTreeQueue(tree *parse.Tree) {
  296. dbQueueLock.Lock()
  297. defer dbQueueLock.Unlock()
  298. newOp := &dbQueueOperation{
  299. renameTree: tree,
  300. inQueueTime: time.Now(),
  301. action: "rename",
  302. }
  303. for i, op := range operationQueue {
  304. if "rename" == op.action && op.renameTree.ID == tree.ID { // 相同树则覆盖
  305. operationQueue[i] = newOp
  306. return
  307. }
  308. }
  309. operationQueue = append(operationQueue, newOp)
  310. }
  311. func RenameSubTreeQueue(tree *parse.Tree) {
  312. dbQueueLock.Lock()
  313. defer dbQueueLock.Unlock()
  314. newOp := &dbQueueOperation{
  315. renameTree: tree,
  316. inQueueTime: time.Now(),
  317. action: "rename_sub_tree",
  318. }
  319. for i, op := range operationQueue {
  320. if "rename_sub_tree" == op.action && op.renameTree.ID == tree.ID { // 相同树则覆盖
  321. operationQueue[i] = newOp
  322. return
  323. }
  324. }
  325. operationQueue = append(operationQueue, newOp)
  326. }
  327. func RemoveTreeQueue(box, rootID string) {
  328. dbQueueLock.Lock()
  329. defer dbQueueLock.Unlock()
  330. newOp := &dbQueueOperation{removeTreeIDBox: box, removeTreeID: rootID, inQueueTime: time.Now(), action: "delete_id"}
  331. for i, op := range operationQueue {
  332. if "delete_id" == op.action && op.removeTreeIDBox == box && op.removeTreeID == rootID {
  333. operationQueue[i] = newOp
  334. return
  335. }
  336. }
  337. operationQueue = append(operationQueue, newOp)
  338. }
  339. func BatchRemoveTreeQueue(rootIDs []string) {
  340. if 1 > len(rootIDs) {
  341. return
  342. }
  343. dbQueueLock.Lock()
  344. defer dbQueueLock.Unlock()
  345. newOp := &dbQueueOperation{removeTreeIDs: rootIDs, inQueueTime: time.Now(), action: "delete_ids"}
  346. operationQueue = append(operationQueue, newOp)
  347. }
  348. func RemoveTreePathQueue(treeBox, treePathPrefix string) {
  349. dbQueueLock.Lock()
  350. defer dbQueueLock.Unlock()
  351. newOp := &dbQueueOperation{removeTreeBox: treeBox, removeTreePath: treePathPrefix, inQueueTime: time.Now(), action: "delete"}
  352. for i, op := range operationQueue {
  353. if "delete" == op.action && (op.removeTreeBox == treeBox && op.removeTreePath == treePathPrefix) {
  354. operationQueue[i] = newOp
  355. return
  356. }
  357. }
  358. operationQueue = append(operationQueue, newOp)
  359. }
  360. func mergeUpsertTrees() (ops []*dbQueueOperation) {
  361. dbQueueLock.Lock()
  362. defer dbQueueLock.Unlock()
  363. ops = operationQueue
  364. operationQueue = nil
  365. return
  366. }