queue.go 11 KB

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