queue.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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/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
  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
  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 failed: %s", 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)
  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 "delete_box":
  152. err = deleteByBoxTx(tx, op.box)
  153. case "delete_box_refs":
  154. err = deleteRefsByBoxTx(tx, op.box)
  155. case "insert_refs":
  156. err = insertRefs(tx, op.upsertTree)
  157. case "update_refs":
  158. err = upsertRefs(tx, op.upsertTree)
  159. case "update_block_content":
  160. err = updateBlockContent(tx, op.block)
  161. case "delete_assets":
  162. err = deleteAssetsByHashes(tx, op.removeAssetHashes)
  163. default:
  164. msg := fmt.Sprintf("unknown operation [%s]", op.action)
  165. logging.LogErrorf(msg)
  166. err = errors.New(msg)
  167. }
  168. return
  169. }
  170. func BatchRemoveAssetsQueue(hashes []string) {
  171. if 1 > len(hashes) {
  172. return
  173. }
  174. dbQueueLock.Lock()
  175. defer dbQueueLock.Unlock()
  176. newOp := &dbQueueOperation{removeAssetHashes: hashes, inQueueTime: time.Now(), action: "delete_assets"}
  177. operationQueue = append(operationQueue, newOp)
  178. }
  179. func UpdateBlockContentQueue(block *Block) {
  180. dbQueueLock.Lock()
  181. defer dbQueueLock.Unlock()
  182. newOp := &dbQueueOperation{block: block, inQueueTime: time.Now(), action: "update_block_content"}
  183. for i, op := range operationQueue {
  184. if "update_block_content" == op.action && op.block.ID == block.ID {
  185. operationQueue[i] = newOp
  186. return
  187. }
  188. }
  189. operationQueue = append(operationQueue, newOp)
  190. }
  191. func UpdateRefsTreeQueue(tree *parse.Tree) {
  192. dbQueueLock.Lock()
  193. defer dbQueueLock.Unlock()
  194. newOp := &dbQueueOperation{upsertTree: tree, inQueueTime: time.Now(), action: "update_refs"}
  195. for i, op := range operationQueue {
  196. if "update_refs" == op.action && op.upsertTree.ID == tree.ID {
  197. operationQueue[i] = newOp
  198. return
  199. }
  200. }
  201. operationQueue = append(operationQueue, newOp)
  202. }
  203. func InsertRefsTreeQueue(tree *parse.Tree) {
  204. dbQueueLock.Lock()
  205. defer dbQueueLock.Unlock()
  206. newOp := &dbQueueOperation{upsertTree: tree, inQueueTime: time.Now(), action: "insert_refs"}
  207. for i, op := range operationQueue {
  208. if "insert_refs" == op.action && op.upsertTree.ID == tree.ID {
  209. operationQueue[i] = newOp
  210. return
  211. }
  212. }
  213. operationQueue = append(operationQueue, newOp)
  214. }
  215. func DeleteBoxRefsQueue(boxID string) {
  216. dbQueueLock.Lock()
  217. defer dbQueueLock.Unlock()
  218. newOp := &dbQueueOperation{box: boxID, inQueueTime: time.Now(), action: "delete_box_refs"}
  219. for i, op := range operationQueue {
  220. if "delete_box_refs" == op.action && op.box == boxID {
  221. operationQueue[i] = newOp
  222. return
  223. }
  224. }
  225. operationQueue = append(operationQueue, newOp)
  226. }
  227. func DeleteBoxQueue(boxID string) {
  228. dbQueueLock.Lock()
  229. defer dbQueueLock.Unlock()
  230. newOp := &dbQueueOperation{box: boxID, inQueueTime: time.Now(), action: "delete_box"}
  231. for i, op := range operationQueue {
  232. if "delete_box" == op.action && op.box == boxID {
  233. operationQueue[i] = newOp
  234. return
  235. }
  236. }
  237. operationQueue = append(operationQueue, newOp)
  238. }
  239. func IndexTreeQueue(box, p string) {
  240. dbQueueLock.Lock()
  241. defer dbQueueLock.Unlock()
  242. newOp := &dbQueueOperation{indexPath: p, box: box, inQueueTime: time.Now(), action: "index"}
  243. for i, op := range operationQueue {
  244. if "index" == op.action && op.indexPath == p && op.box == box { // 相同树则覆盖
  245. operationQueue[i] = newOp
  246. return
  247. }
  248. }
  249. operationQueue = append(operationQueue, newOp)
  250. }
  251. func UpsertTreeQueue(tree *parse.Tree) {
  252. dbQueueLock.Lock()
  253. defer dbQueueLock.Unlock()
  254. newOp := &dbQueueOperation{upsertTree: tree, inQueueTime: time.Now(), action: "upsert"}
  255. for i, op := range operationQueue {
  256. if "upsert" == op.action && op.upsertTree.ID == tree.ID { // 相同树则覆盖
  257. operationQueue[i] = newOp
  258. return
  259. }
  260. }
  261. operationQueue = append(operationQueue, newOp)
  262. }
  263. func RenameTreeQueue(tree *parse.Tree) {
  264. dbQueueLock.Lock()
  265. defer dbQueueLock.Unlock()
  266. newOp := &dbQueueOperation{
  267. renameTree: tree,
  268. inQueueTime: time.Now(),
  269. action: "rename",
  270. }
  271. for i, op := range operationQueue {
  272. if "rename" == op.action && op.renameTree.ID == tree.ID { // 相同树则覆盖
  273. operationQueue[i] = newOp
  274. return
  275. }
  276. }
  277. operationQueue = append(operationQueue, newOp)
  278. }
  279. func RemoveTreeQueue(box, rootID string) {
  280. dbQueueLock.Lock()
  281. defer dbQueueLock.Unlock()
  282. newOp := &dbQueueOperation{removeTreeIDBox: box, removeTreeID: rootID, inQueueTime: time.Now(), action: "delete_id"}
  283. for i, op := range operationQueue {
  284. if "delete_id" == op.action && op.removeTreeIDBox == box && op.removeTreeID == rootID {
  285. operationQueue[i] = newOp
  286. return
  287. }
  288. }
  289. operationQueue = append(operationQueue, newOp)
  290. }
  291. func BatchRemoveTreeQueue(rootIDs []string) {
  292. if 1 > len(rootIDs) {
  293. return
  294. }
  295. dbQueueLock.Lock()
  296. defer dbQueueLock.Unlock()
  297. newOp := &dbQueueOperation{removeTreeIDs: rootIDs, inQueueTime: time.Now(), action: "delete_ids"}
  298. operationQueue = append(operationQueue, newOp)
  299. }
  300. func RemoveTreePathQueue(treeBox, treePathPrefix string) {
  301. dbQueueLock.Lock()
  302. defer dbQueueLock.Unlock()
  303. newOp := &dbQueueOperation{removeTreeBox: treeBox, removeTreePath: treePathPrefix, inQueueTime: time.Now(), action: "delete"}
  304. for i, op := range operationQueue {
  305. if "delete" == op.action && (op.removeTreeBox == treeBox && op.removeTreePath == treePathPrefix) {
  306. operationQueue[i] = newOp
  307. return
  308. }
  309. }
  310. operationQueue = append(operationQueue, newOp)
  311. }
  312. func mergeUpsertTrees() (ops []*dbQueueOperation) {
  313. dbQueueLock.Lock()
  314. defer dbQueueLock.Unlock()
  315. ops = operationQueue
  316. operationQueue = nil
  317. return
  318. }