queue.go 9.8 KB

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