queue.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. // SiYuan - Refactor your thinking
  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. //
  182. //newOp := &dbQueueOperation{av: av, inQueueTime: time.Now(), action: "av_rebuild"}
  183. //for i, op := range operationQueue {
  184. // if "av_rebuild" == op.action && op.av.ID == av.ID {
  185. // operationQueue[i] = newOp
  186. // return
  187. // }
  188. //}
  189. //operationQueue = append(operationQueue, newOp)
  190. }
  191. func BatchRemoveAssetsQueue(hashes []string) {
  192. if 1 > len(hashes) {
  193. return
  194. }
  195. dbQueueLock.Lock()
  196. defer dbQueueLock.Unlock()
  197. newOp := &dbQueueOperation{removeAssetHashes: hashes, inQueueTime: time.Now(), action: "delete_assets"}
  198. operationQueue = append(operationQueue, newOp)
  199. }
  200. func UpdateBlockContentQueue(block *Block) {
  201. dbQueueLock.Lock()
  202. defer dbQueueLock.Unlock()
  203. newOp := &dbQueueOperation{block: block, inQueueTime: time.Now(), action: "update_block_content"}
  204. for i, op := range operationQueue {
  205. if "update_block_content" == op.action && op.block.ID == block.ID {
  206. operationQueue[i] = newOp
  207. return
  208. }
  209. }
  210. operationQueue = append(operationQueue, newOp)
  211. }
  212. func DeleteRefsTreeQueue(tree *parse.Tree) {
  213. dbQueueLock.Lock()
  214. defer dbQueueLock.Unlock()
  215. newOp := &dbQueueOperation{upsertTree: tree, inQueueTime: time.Now(), action: "delete_refs"}
  216. for i, op := range operationQueue {
  217. if "delete_refs" == op.action && op.upsertTree.ID == tree.ID {
  218. operationQueue[i] = newOp
  219. return
  220. }
  221. }
  222. operationQueue = append(operationQueue, newOp)
  223. }
  224. func UpdateRefsTreeQueue(tree *parse.Tree) {
  225. dbQueueLock.Lock()
  226. defer dbQueueLock.Unlock()
  227. newOp := &dbQueueOperation{upsertTree: tree, inQueueTime: time.Now(), action: "update_refs"}
  228. for i, op := range operationQueue {
  229. if "update_refs" == op.action && op.upsertTree.ID == tree.ID {
  230. operationQueue[i] = newOp
  231. return
  232. }
  233. }
  234. operationQueue = append(operationQueue, newOp)
  235. }
  236. func InsertRefsTreeQueue(tree *parse.Tree) {
  237. dbQueueLock.Lock()
  238. defer dbQueueLock.Unlock()
  239. newOp := &dbQueueOperation{upsertTree: tree, inQueueTime: time.Now(), action: "insert_refs"}
  240. for i, op := range operationQueue {
  241. if "insert_refs" == op.action && op.upsertTree.ID == tree.ID {
  242. operationQueue[i] = newOp
  243. return
  244. }
  245. }
  246. operationQueue = append(operationQueue, newOp)
  247. }
  248. func DeleteBoxRefsQueue(boxID string) {
  249. dbQueueLock.Lock()
  250. defer dbQueueLock.Unlock()
  251. newOp := &dbQueueOperation{box: boxID, inQueueTime: time.Now(), action: "delete_box_refs"}
  252. for i, op := range operationQueue {
  253. if "delete_box_refs" == op.action && op.box == boxID {
  254. operationQueue[i] = newOp
  255. return
  256. }
  257. }
  258. operationQueue = append(operationQueue, newOp)
  259. }
  260. func DeleteBoxQueue(boxID string) {
  261. dbQueueLock.Lock()
  262. defer dbQueueLock.Unlock()
  263. newOp := &dbQueueOperation{box: boxID, inQueueTime: time.Now(), action: "delete_box"}
  264. for i, op := range operationQueue {
  265. if "delete_box" == op.action && op.box == boxID {
  266. operationQueue[i] = newOp
  267. return
  268. }
  269. }
  270. operationQueue = append(operationQueue, newOp)
  271. }
  272. func IndexTreeQueue(box, p string) {
  273. dbQueueLock.Lock()
  274. defer dbQueueLock.Unlock()
  275. newOp := &dbQueueOperation{indexPath: p, box: box, inQueueTime: time.Now(), action: "index"}
  276. for i, op := range operationQueue {
  277. if "index" == op.action && op.indexPath == p && op.box == box { // 相同树则覆盖
  278. operationQueue[i] = newOp
  279. return
  280. }
  281. }
  282. operationQueue = append(operationQueue, newOp)
  283. }
  284. func UpsertTreeQueue(tree *parse.Tree) {
  285. dbQueueLock.Lock()
  286. defer dbQueueLock.Unlock()
  287. newOp := &dbQueueOperation{upsertTree: tree, inQueueTime: time.Now(), action: "upsert"}
  288. for i, op := range operationQueue {
  289. if "upsert" == op.action && op.upsertTree.ID == tree.ID { // 相同树则覆盖
  290. operationQueue[i] = newOp
  291. return
  292. }
  293. }
  294. operationQueue = append(operationQueue, newOp)
  295. }
  296. func RenameTreeQueue(tree *parse.Tree) {
  297. dbQueueLock.Lock()
  298. defer dbQueueLock.Unlock()
  299. newOp := &dbQueueOperation{
  300. renameTree: tree,
  301. inQueueTime: time.Now(),
  302. action: "rename",
  303. }
  304. for i, op := range operationQueue {
  305. if "rename" == op.action && op.renameTree.ID == tree.ID { // 相同树则覆盖
  306. operationQueue[i] = newOp
  307. return
  308. }
  309. }
  310. operationQueue = append(operationQueue, newOp)
  311. }
  312. func RenameSubTreeQueue(tree *parse.Tree) {
  313. dbQueueLock.Lock()
  314. defer dbQueueLock.Unlock()
  315. newOp := &dbQueueOperation{
  316. renameTree: tree,
  317. inQueueTime: time.Now(),
  318. action: "rename_sub_tree",
  319. }
  320. for i, op := range operationQueue {
  321. if "rename_sub_tree" == op.action && op.renameTree.ID == tree.ID { // 相同树则覆盖
  322. operationQueue[i] = newOp
  323. return
  324. }
  325. }
  326. operationQueue = append(operationQueue, newOp)
  327. }
  328. func RemoveTreeQueue(box, rootID string) {
  329. dbQueueLock.Lock()
  330. defer dbQueueLock.Unlock()
  331. newOp := &dbQueueOperation{removeTreeIDBox: box, removeTreeID: rootID, inQueueTime: time.Now(), action: "delete_id"}
  332. for i, op := range operationQueue {
  333. if "delete_id" == op.action && op.removeTreeIDBox == box && op.removeTreeID == rootID {
  334. operationQueue[i] = newOp
  335. return
  336. }
  337. }
  338. operationQueue = append(operationQueue, newOp)
  339. }
  340. func BatchRemoveTreeQueue(rootIDs []string) {
  341. if 1 > len(rootIDs) {
  342. return
  343. }
  344. dbQueueLock.Lock()
  345. defer dbQueueLock.Unlock()
  346. newOp := &dbQueueOperation{removeTreeIDs: rootIDs, inQueueTime: time.Now(), action: "delete_ids"}
  347. operationQueue = append(operationQueue, newOp)
  348. }
  349. func RemoveTreePathQueue(treeBox, treePathPrefix string) {
  350. dbQueueLock.Lock()
  351. defer dbQueueLock.Unlock()
  352. newOp := &dbQueueOperation{removeTreeBox: treeBox, removeTreePath: treePathPrefix, inQueueTime: time.Now(), action: "delete"}
  353. for i, op := range operationQueue {
  354. if "delete" == op.action && (op.removeTreeBox == treeBox && op.removeTreePath == treePathPrefix) {
  355. operationQueue[i] = newOp
  356. return
  357. }
  358. }
  359. operationQueue = append(operationQueue, newOp)
  360. }
  361. func mergeUpsertTrees() (ops []*dbQueueOperation) {
  362. dbQueueLock.Lock()
  363. defer dbQueueLock.Unlock()
  364. ops = operationQueue
  365. operationQueue = nil
  366. return
  367. }