queue.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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"
  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
  39. indexPath string // index
  40. upsertTree *parse.Tree // upsert/insert_refs
  41. removeTreeBox, removeTreePath string // delete
  42. removeTreeIDBox, removeTreeID string // delete_id
  43. box string // delete_box/delete_box_refs/index
  44. renameTree *parse.Tree // rename
  45. renameTreeOldHPath string // rename
  46. }
  47. func AutoFlushTx() {
  48. for {
  49. time.Sleep(util.SQLFlushInterval)
  50. task.AppendTask(task.DatabaseIndexCommit, FlushQueue)
  51. }
  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. for i, op := range ops {
  94. if util.IsExiting {
  95. return
  96. }
  97. tx, err := beginTx()
  98. if nil != err {
  99. return
  100. }
  101. context["current"] = i
  102. context["total"] = total
  103. if err = execOp(op, tx, context); nil != err {
  104. logging.LogErrorf("queue operation failed: %s", err)
  105. return
  106. }
  107. if err = commitTx(tx); nil != err {
  108. logging.LogErrorf("commit tx failed: %s", err)
  109. return
  110. }
  111. if 16 < i && 0 == i%256 {
  112. runtime.GC()
  113. }
  114. }
  115. elapsed := time.Now().Sub(start).Milliseconds()
  116. if 5000 < elapsed {
  117. logging.LogInfof("op tx [%dms]", elapsed)
  118. }
  119. }
  120. func execOp(op *dbQueueOperation, tx *sql.Tx, context map[string]interface{}) (err error) {
  121. switch op.action {
  122. case "index":
  123. err = indexTree(tx, op.box, op.indexPath, context)
  124. case "upsert":
  125. err = upsertTree(tx, op.upsertTree, context)
  126. case "delete":
  127. err = batchDeleteByPathPrefix(tx, op.removeTreeBox, op.removeTreePath)
  128. case "delete_id":
  129. err = deleteByRootID(tx, op.removeTreeID, context)
  130. case "rename":
  131. err = batchUpdateHPath(tx, op.renameTree.Box, op.renameTree.ID, op.renameTreeOldHPath, op.renameTree.HPath)
  132. if nil != err {
  133. break
  134. }
  135. err = updateRootContent(tx, path.Base(op.renameTree.HPath), op.renameTree.Root.IALAttr("updated"), op.renameTree.ID)
  136. case "delete_box":
  137. err = deleteByBoxTx(tx, op.box)
  138. case "delete_box_refs":
  139. err = deleteRefsByBoxTx(tx, op.box)
  140. case "insert_refs":
  141. err = insertRefs(tx, op.upsertTree)
  142. case "update_refs":
  143. err = upsertRefs(tx, op.upsertTree)
  144. default:
  145. msg := fmt.Sprintf("unknown operation [%s]", op.action)
  146. logging.LogErrorf(msg)
  147. err = errors.New(msg)
  148. }
  149. return
  150. }
  151. func mergeUpsertTrees() (ops []*dbQueueOperation) {
  152. dbQueueLock.Lock()
  153. defer dbQueueLock.Unlock()
  154. ops = operationQueue
  155. operationQueue = nil
  156. return
  157. }
  158. func UpdateRefsTreeQueue(tree *parse.Tree) {
  159. dbQueueLock.Lock()
  160. defer dbQueueLock.Unlock()
  161. newOp := &dbQueueOperation{upsertTree: tree, inQueueTime: time.Now(), action: "update_refs"}
  162. for i, op := range operationQueue {
  163. if "update_refs" == op.action && op.upsertTree.ID == tree.ID {
  164. operationQueue[i] = newOp
  165. return
  166. }
  167. }
  168. operationQueue = append(operationQueue, newOp)
  169. }
  170. func InsertRefsTreeQueue(tree *parse.Tree) {
  171. dbQueueLock.Lock()
  172. defer dbQueueLock.Unlock()
  173. newOp := &dbQueueOperation{upsertTree: tree, inQueueTime: time.Now(), action: "insert_refs"}
  174. for i, op := range operationQueue {
  175. if "insert_refs" == op.action && op.upsertTree.ID == tree.ID {
  176. operationQueue[i] = newOp
  177. return
  178. }
  179. }
  180. operationQueue = append(operationQueue, newOp)
  181. }
  182. func DeleteBoxRefsQueue(boxID string) {
  183. dbQueueLock.Lock()
  184. defer dbQueueLock.Unlock()
  185. newOp := &dbQueueOperation{box: boxID, inQueueTime: time.Now(), action: "delete_box_refs"}
  186. for i, op := range operationQueue {
  187. if "delete_box_refs" == op.action && op.box == boxID {
  188. operationQueue[i] = newOp
  189. return
  190. }
  191. }
  192. operationQueue = append(operationQueue, newOp)
  193. }
  194. func DeleteBoxQueue(boxID string) {
  195. dbQueueLock.Lock()
  196. defer dbQueueLock.Unlock()
  197. newOp := &dbQueueOperation{box: boxID, inQueueTime: time.Now(), action: "delete_box"}
  198. for i, op := range operationQueue {
  199. if "delete_box" == op.action && op.box == boxID {
  200. operationQueue[i] = newOp
  201. return
  202. }
  203. }
  204. operationQueue = append(operationQueue, newOp)
  205. }
  206. func IndexTreeQueue(box, p string) {
  207. dbQueueLock.Lock()
  208. defer dbQueueLock.Unlock()
  209. newOp := &dbQueueOperation{indexPath: p, box: box, inQueueTime: time.Now(), action: "index"}
  210. for i, op := range operationQueue {
  211. if "index" == op.action && op.indexPath == p && op.box == box { // 相同树则覆盖
  212. operationQueue[i] = newOp
  213. return
  214. }
  215. }
  216. operationQueue = append(operationQueue, newOp)
  217. }
  218. func UpsertTreeQueue(tree *parse.Tree) {
  219. dbQueueLock.Lock()
  220. defer dbQueueLock.Unlock()
  221. newOp := &dbQueueOperation{upsertTree: tree, inQueueTime: time.Now(), action: "upsert"}
  222. for i, op := range operationQueue {
  223. if "upsert" == op.action && op.upsertTree.ID == tree.ID { // 相同树则覆盖
  224. operationQueue[i] = newOp
  225. return
  226. }
  227. }
  228. operationQueue = append(operationQueue, newOp)
  229. }
  230. func RenameTreeQueue(tree *parse.Tree, oldHPath string) {
  231. dbQueueLock.Lock()
  232. defer dbQueueLock.Unlock()
  233. newOp := &dbQueueOperation{
  234. renameTree: tree,
  235. renameTreeOldHPath: oldHPath,
  236. inQueueTime: time.Now(),
  237. action: "rename"}
  238. for i, op := range operationQueue {
  239. if "rename" == op.action && op.renameTree.ID == tree.ID { // 相同树则覆盖
  240. operationQueue[i] = newOp
  241. return
  242. }
  243. }
  244. operationQueue = append(operationQueue, newOp)
  245. }
  246. func RemoveTreeQueue(box, rootID string) {
  247. dbQueueLock.Lock()
  248. defer dbQueueLock.Unlock()
  249. newOp := &dbQueueOperation{removeTreeIDBox: box, removeTreeID: rootID, inQueueTime: time.Now(), action: "delete_id"}
  250. for i, op := range operationQueue {
  251. if "delete_id" == op.action && op.removeTreeIDBox == box && op.removeTreeID == rootID {
  252. operationQueue[i] = newOp
  253. return
  254. }
  255. }
  256. operationQueue = append(operationQueue, newOp)
  257. }
  258. func RemoveTreePathQueue(treeBox, treePathPrefix string) {
  259. dbQueueLock.Lock()
  260. defer dbQueueLock.Unlock()
  261. newOp := &dbQueueOperation{removeTreeBox: treeBox, removeTreePath: treePathPrefix, inQueueTime: time.Now(), action: "delete"}
  262. for i, op := range operationQueue {
  263. if "delete" == op.action && (op.removeTreeBox == treeBox && op.removeTreePath == treePathPrefix) {
  264. operationQueue[i] = newOp
  265. return
  266. }
  267. }
  268. operationQueue = append(operationQueue, newOp)
  269. }