queue.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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/task"
  29. "github.com/siyuan-note/siyuan/kernel/util"
  30. )
  31. var (
  32. operationQueue []*dbQueueOperation
  33. dbQueueLock = sync.Mutex{}
  34. txLock = sync.Mutex{}
  35. )
  36. type dbQueueOperation struct {
  37. inQueueTime time.Time
  38. 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
  39. indexPath string // index
  40. upsertTree *parse.Tree // upsert/insert_refs/update_refs/delete_refs
  41. removeTreeBox, removeTreePath string // delete
  42. removeTreeIDBox, removeTreeID string // delete_id
  43. removeTreeIDs []string // delete_ids
  44. box string // delete_box/delete_box_refs/index
  45. renameTree *parse.Tree // rename/rename_sub_tree
  46. block *Block // update_block_content
  47. removeAssetHashes []string // delete_assets
  48. }
  49. func FlushTxJob() {
  50. task.AppendTask(task.DatabaseIndexCommit, FlushQueue)
  51. }
  52. func WaitForWritingDatabase() {
  53. var printLog bool
  54. var lastPrintLog bool
  55. for i := 0; isWritingDatabase(); i++ {
  56. time.Sleep(50 * time.Millisecond)
  57. if 200 < i && !printLog { // 10s 后打日志
  58. logging.LogWarnf("database is writing: \n%s", logging.ShortStack())
  59. printLog = true
  60. }
  61. if 1200 < i && !lastPrintLog { // 60s 后打日志
  62. logging.LogWarnf("database is still writing")
  63. lastPrintLog = true
  64. }
  65. }
  66. }
  67. func isWritingDatabase() bool {
  68. time.Sleep(util.SQLFlushInterval + 50*time.Millisecond)
  69. if 0 < len(operationQueue) || util.IsMutexLocked(&txLock) {
  70. return true
  71. }
  72. return false
  73. }
  74. func IsEmptyQueue() bool {
  75. return 1 > len(operationQueue) && !util.IsMutexLocked(&txLock)
  76. }
  77. func ClearQueue() {
  78. dbQueueLock.Lock()
  79. defer dbQueueLock.Unlock()
  80. operationQueue = nil
  81. }
  82. func FlushQueue() {
  83. ops := mergeUpsertTrees()
  84. if 1 > len(ops) {
  85. return
  86. }
  87. txLock.Lock()
  88. defer txLock.Unlock()
  89. start := time.Now()
  90. context := map[string]interface{}{eventbus.CtxPushMsg: eventbus.CtxPushMsgToStatusBar}
  91. total := len(ops)
  92. if 512 < total {
  93. disableCache()
  94. defer enableCache()
  95. }
  96. groupOpsTotal := map[string]int{}
  97. for _, op := range ops {
  98. groupOpsTotal[op.action]++
  99. }
  100. groupOpsCurrent := map[string]int{}
  101. for i, op := range ops {
  102. if util.IsExiting {
  103. return
  104. }
  105. tx, err := beginTx()
  106. if nil != err {
  107. return
  108. }
  109. groupOpsCurrent[op.action]++
  110. context["current"] = groupOpsCurrent[op.action]
  111. context["total"] = groupOpsTotal[op.action]
  112. if err = execOp(op, tx, context); nil != err {
  113. tx.Rollback()
  114. logging.LogErrorf("queue operation [%s] failed: %s", op.action, err)
  115. continue
  116. }
  117. if err = commitTx(tx); nil != err {
  118. logging.LogErrorf("commit tx failed: %s", err)
  119. return
  120. }
  121. if 16 < i && 0 == i%128 {
  122. debug.FreeOSMemory()
  123. }
  124. }
  125. if 128 < len(ops) {
  126. debug.FreeOSMemory()
  127. }
  128. elapsed := time.Now().Sub(start).Milliseconds()
  129. if 7000 < elapsed {
  130. logging.LogInfof("database op tx [%dms]", elapsed)
  131. }
  132. }
  133. func execOp(op *dbQueueOperation, tx *sql.Tx, context map[string]interface{}) (err error) {
  134. switch op.action {
  135. case "index":
  136. err = indexTree(tx, op.box, op.indexPath, context)
  137. case "upsert":
  138. err = upsertTree(tx, op.upsertTree, context)
  139. case "delete":
  140. err = batchDeleteByPathPrefix(tx, op.removeTreeBox, op.removeTreePath)
  141. case "delete_id":
  142. err = deleteByRootID(tx, op.removeTreeID, context)
  143. case "delete_ids":
  144. err = batchDeleteByRootIDs(tx, op.removeTreeIDs, context)
  145. case "rename":
  146. err = batchUpdateHPath(tx, op.renameTree.Box, op.renameTree.ID, op.renameTree.HPath, context)
  147. if nil != err {
  148. break
  149. }
  150. err = updateRootContent(tx, path.Base(op.renameTree.HPath), op.renameTree.Root.IALAttr("updated"), op.renameTree.ID)
  151. case "rename_sub_tree":
  152. err = batchUpdateHPath(tx, op.renameTree.Box, op.renameTree.ID, op.renameTree.HPath, context)
  153. case "delete_box":
  154. err = deleteByBoxTx(tx, op.box)
  155. case "delete_box_refs":
  156. err = deleteRefsByBoxTx(tx, op.box)
  157. case "insert_refs":
  158. err = insertRefs(tx, op.upsertTree)
  159. case "update_refs":
  160. err = upsertRefs(tx, op.upsertTree)
  161. case "delete_refs":
  162. err = deleteRefs(tx, op.upsertTree)
  163. case "update_block_content":
  164. err = updateBlockContent(tx, op.block)
  165. case "delete_assets":
  166. err = deleteAssetsByHashes(tx, op.removeAssetHashes)
  167. default:
  168. msg := fmt.Sprintf("unknown operation [%s]", op.action)
  169. logging.LogErrorf(msg)
  170. err = errors.New(msg)
  171. }
  172. return
  173. }
  174. func BatchRemoveAssetsQueue(hashes []string) {
  175. if 1 > len(hashes) {
  176. return
  177. }
  178. dbQueueLock.Lock()
  179. defer dbQueueLock.Unlock()
  180. newOp := &dbQueueOperation{removeAssetHashes: hashes, inQueueTime: time.Now(), action: "delete_assets"}
  181. operationQueue = append(operationQueue, newOp)
  182. }
  183. func UpdateBlockContentQueue(block *Block) {
  184. dbQueueLock.Lock()
  185. defer dbQueueLock.Unlock()
  186. newOp := &dbQueueOperation{block: block, inQueueTime: time.Now(), action: "update_block_content"}
  187. for i, op := range operationQueue {
  188. if "update_block_content" == op.action && op.block.ID == block.ID {
  189. operationQueue[i] = newOp
  190. return
  191. }
  192. }
  193. operationQueue = append(operationQueue, newOp)
  194. }
  195. func DeleteRefsTreeQueue(tree *parse.Tree) {
  196. dbQueueLock.Lock()
  197. defer dbQueueLock.Unlock()
  198. newOp := &dbQueueOperation{upsertTree: tree, inQueueTime: time.Now(), action: "delete_refs"}
  199. for i, op := range operationQueue {
  200. if "delete_refs" == op.action && op.upsertTree.ID == tree.ID {
  201. operationQueue[i] = newOp
  202. return
  203. }
  204. }
  205. operationQueue = append(operationQueue, newOp)
  206. }
  207. func UpdateRefsTreeQueue(tree *parse.Tree) {
  208. dbQueueLock.Lock()
  209. defer dbQueueLock.Unlock()
  210. newOp := &dbQueueOperation{upsertTree: tree, inQueueTime: time.Now(), action: "update_refs"}
  211. for i, op := range operationQueue {
  212. if "update_refs" == op.action && op.upsertTree.ID == tree.ID {
  213. operationQueue[i] = newOp
  214. return
  215. }
  216. }
  217. operationQueue = append(operationQueue, newOp)
  218. }
  219. func InsertRefsTreeQueue(tree *parse.Tree) {
  220. dbQueueLock.Lock()
  221. defer dbQueueLock.Unlock()
  222. newOp := &dbQueueOperation{upsertTree: tree, inQueueTime: time.Now(), action: "insert_refs"}
  223. for i, op := range operationQueue {
  224. if "insert_refs" == op.action && op.upsertTree.ID == tree.ID {
  225. operationQueue[i] = newOp
  226. return
  227. }
  228. }
  229. operationQueue = append(operationQueue, newOp)
  230. }
  231. func DeleteBoxRefsQueue(boxID string) {
  232. dbQueueLock.Lock()
  233. defer dbQueueLock.Unlock()
  234. newOp := &dbQueueOperation{box: boxID, inQueueTime: time.Now(), action: "delete_box_refs"}
  235. for i, op := range operationQueue {
  236. if "delete_box_refs" == op.action && op.box == boxID {
  237. operationQueue[i] = newOp
  238. return
  239. }
  240. }
  241. operationQueue = append(operationQueue, newOp)
  242. }
  243. func DeleteBoxQueue(boxID string) {
  244. dbQueueLock.Lock()
  245. defer dbQueueLock.Unlock()
  246. newOp := &dbQueueOperation{box: boxID, inQueueTime: time.Now(), action: "delete_box"}
  247. for i, op := range operationQueue {
  248. if "delete_box" == op.action && op.box == boxID {
  249. operationQueue[i] = newOp
  250. return
  251. }
  252. }
  253. operationQueue = append(operationQueue, newOp)
  254. }
  255. func IndexTreeQueue(box, p string) {
  256. dbQueueLock.Lock()
  257. defer dbQueueLock.Unlock()
  258. newOp := &dbQueueOperation{indexPath: p, box: box, inQueueTime: time.Now(), action: "index"}
  259. for i, op := range operationQueue {
  260. if "index" == op.action && op.indexPath == p && op.box == box { // 相同树则覆盖
  261. operationQueue[i] = newOp
  262. return
  263. }
  264. }
  265. operationQueue = append(operationQueue, newOp)
  266. }
  267. func UpsertTreeQueue(tree *parse.Tree) {
  268. dbQueueLock.Lock()
  269. defer dbQueueLock.Unlock()
  270. newOp := &dbQueueOperation{upsertTree: tree, inQueueTime: time.Now(), action: "upsert"}
  271. for i, op := range operationQueue {
  272. if "upsert" == op.action && op.upsertTree.ID == tree.ID { // 相同树则覆盖
  273. operationQueue[i] = newOp
  274. return
  275. }
  276. }
  277. operationQueue = append(operationQueue, newOp)
  278. }
  279. func RenameTreeQueue(tree *parse.Tree) {
  280. dbQueueLock.Lock()
  281. defer dbQueueLock.Unlock()
  282. newOp := &dbQueueOperation{
  283. renameTree: tree,
  284. inQueueTime: time.Now(),
  285. action: "rename",
  286. }
  287. for i, op := range operationQueue {
  288. if "rename" == op.action && op.renameTree.ID == tree.ID { // 相同树则覆盖
  289. operationQueue[i] = newOp
  290. return
  291. }
  292. }
  293. operationQueue = append(operationQueue, newOp)
  294. }
  295. func RenameSubTreeQueue(tree *parse.Tree) {
  296. dbQueueLock.Lock()
  297. defer dbQueueLock.Unlock()
  298. newOp := &dbQueueOperation{
  299. renameTree: tree,
  300. inQueueTime: time.Now(),
  301. action: "rename_sub_tree",
  302. }
  303. for i, op := range operationQueue {
  304. if "rename_sub_tree" == op.action && op.renameTree.ID == tree.ID { // 相同树则覆盖
  305. operationQueue[i] = newOp
  306. return
  307. }
  308. }
  309. operationQueue = append(operationQueue, newOp)
  310. }
  311. func RemoveTreeQueue(box, rootID string) {
  312. dbQueueLock.Lock()
  313. defer dbQueueLock.Unlock()
  314. newOp := &dbQueueOperation{removeTreeIDBox: box, removeTreeID: rootID, inQueueTime: time.Now(), action: "delete_id"}
  315. for i, op := range operationQueue {
  316. if "delete_id" == op.action && op.removeTreeIDBox == box && op.removeTreeID == rootID {
  317. operationQueue[i] = newOp
  318. return
  319. }
  320. }
  321. operationQueue = append(operationQueue, newOp)
  322. }
  323. func BatchRemoveTreeQueue(rootIDs []string) {
  324. if 1 > len(rootIDs) {
  325. return
  326. }
  327. dbQueueLock.Lock()
  328. defer dbQueueLock.Unlock()
  329. newOp := &dbQueueOperation{removeTreeIDs: rootIDs, inQueueTime: time.Now(), action: "delete_ids"}
  330. operationQueue = append(operationQueue, newOp)
  331. }
  332. func RemoveTreePathQueue(treeBox, treePathPrefix string) {
  333. dbQueueLock.Lock()
  334. defer dbQueueLock.Unlock()
  335. newOp := &dbQueueOperation{removeTreeBox: treeBox, removeTreePath: treePathPrefix, inQueueTime: time.Now(), action: "delete"}
  336. for i, op := range operationQueue {
  337. if "delete" == op.action && (op.removeTreeBox == treeBox && op.removeTreePath == treePathPrefix) {
  338. operationQueue[i] = newOp
  339. return
  340. }
  341. }
  342. operationQueue = append(operationQueue, newOp)
  343. }
  344. func mergeUpsertTrees() (ops []*dbQueueOperation) {
  345. dbQueueLock.Lock()
  346. defer dbQueueLock.Unlock()
  347. ops = operationQueue
  348. operationQueue = nil
  349. return
  350. }