queue.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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 task
  17. import (
  18. "context"
  19. "reflect"
  20. "sync"
  21. "time"
  22. "github.com/88250/gulu"
  23. "github.com/siyuan-note/logging"
  24. "github.com/siyuan-note/siyuan/kernel/util"
  25. )
  26. var (
  27. taskQueue []*Task
  28. queueLock = sync.Mutex{}
  29. )
  30. type Task struct {
  31. Action string
  32. Handler reflect.Value
  33. Args []interface{}
  34. Created time.Time
  35. Timeout time.Duration
  36. }
  37. func AppendTask(action string, handler interface{}, args ...interface{}) {
  38. AppendTaskWithTimeout(action, 24*time.Hour, handler, args...)
  39. }
  40. func AppendTaskWithTimeout(action string, timeout time.Duration, handler interface{}, args ...interface{}) {
  41. if util.IsExiting {
  42. //logging.LogWarnf("task queue is paused, action [%s] will be ignored", action)
  43. return
  44. }
  45. currentActions := getCurrentActions()
  46. if gulu.Str.Contains(action, currentActions) && gulu.Str.Contains(action, uniqueActions) {
  47. //logging.LogWarnf("task [%s] is already in queue, will be ignored", action)
  48. return
  49. }
  50. queueLock.Lock()
  51. defer queueLock.Unlock()
  52. taskQueue = append(taskQueue, &Task{
  53. Action: action,
  54. Timeout: timeout,
  55. Handler: reflect.ValueOf(handler),
  56. Args: args,
  57. Created: time.Now(),
  58. })
  59. }
  60. func getCurrentActions() (ret []string) {
  61. queueLock.Lock()
  62. defer queueLock.Unlock()
  63. if "" != currentTaskAction {
  64. ret = append(ret, currentTaskAction)
  65. }
  66. for _, task := range taskQueue {
  67. ret = append(ret, task.Action)
  68. }
  69. return
  70. }
  71. const (
  72. RepoCheckout = "task.repo.checkout" // 从快照中检出
  73. DatabaseIndexFull = "task.database.index.full" // 重建索引
  74. DatabaseIndex = "task.database.index" // 数据库索引
  75. DatabaseIndexCommit = "task.database.index.commit" // 数据库索引提交
  76. DatabaseIndexRef = "task.database.index.ref" // 数据库索引引用
  77. DatabaseIndexFix = "task.database.index.fix" // 数据库索引订正
  78. OCRImage = "task.ocr.image" // 图片 OCR 提取文本
  79. HistoryGenerateDoc = "task.history.generateDoc" // 生成文件历史
  80. HistoryDatabaseIndexCommit = "task.history.database.index.commit" // 历史数据库索引提交
  81. DatabaseIndexEmbedBlock = "task.database.index.embedBlock" // 数据库索引嵌入块
  82. ReloadUI = "task.reload.ui" // 重载 UI
  83. UpgradeUserGuide = "task.upgrade.userGuide" // 升级用户指南文档笔记本
  84. )
  85. // uniqueActions 描述了唯一的任务,即队列中只能存在一个在执行的任务。
  86. var uniqueActions = []string{
  87. RepoCheckout,
  88. DatabaseIndexFull,
  89. DatabaseIndexCommit,
  90. OCRImage,
  91. HistoryGenerateDoc,
  92. HistoryDatabaseIndexCommit,
  93. DatabaseIndexEmbedBlock,
  94. }
  95. func Contain(action string, moreActions ...string) bool {
  96. actions := append(moreActions, action)
  97. actions = gulu.Str.RemoveDuplicatedElem(actions)
  98. for _, task := range taskQueue {
  99. if gulu.Str.Contains(task.Action, actions) {
  100. return true
  101. }
  102. }
  103. return false
  104. }
  105. func StatusJob() {
  106. tasks := taskQueue
  107. var items []map[string]interface{}
  108. count := map[string]int{}
  109. actionLangs := util.TaskActionLangs[util.Lang]
  110. for _, task := range tasks {
  111. action := task.Action
  112. if c := count[action]; 2 < c {
  113. logging.LogWarnf("too many tasks [%s], ignore show its status", action)
  114. continue
  115. }
  116. count[action]++
  117. if nil != actionLangs {
  118. if label := actionLangs[task.Action]; nil != label {
  119. action = label.(string)
  120. }
  121. }
  122. item := map[string]interface{}{"action": action}
  123. items = append(items, item)
  124. }
  125. if "" != currentTaskAction {
  126. if nil != actionLangs {
  127. if label := actionLangs[currentTaskAction]; nil != label {
  128. items = append([]map[string]interface{}{{"action": label.(string)}}, items...)
  129. }
  130. }
  131. }
  132. if 1 > len(items) {
  133. items = []map[string]interface{}{}
  134. }
  135. data := map[string]interface{}{}
  136. data["tasks"] = items
  137. util.PushBackgroundTask(data)
  138. }
  139. func ExecTaskJob() {
  140. task := popTask()
  141. if nil == task {
  142. return
  143. }
  144. if util.IsExiting {
  145. return
  146. }
  147. execTask(task)
  148. }
  149. func popTask() (ret *Task) {
  150. queueLock.Lock()
  151. defer queueLock.Unlock()
  152. if 0 == len(taskQueue) {
  153. return
  154. }
  155. ret = taskQueue[0]
  156. taskQueue = taskQueue[1:]
  157. return
  158. }
  159. var currentTaskAction string
  160. func execTask(task *Task) {
  161. defer logging.Recover()
  162. args := make([]reflect.Value, len(task.Args))
  163. for i, v := range task.Args {
  164. if nil == v {
  165. args[i] = reflect.New(task.Handler.Type().In(i)).Elem()
  166. } else {
  167. args[i] = reflect.ValueOf(v)
  168. }
  169. }
  170. currentTaskAction = task.Action
  171. ctx, cancel := context.WithTimeout(context.Background(), task.Timeout)
  172. defer cancel()
  173. ch := make(chan bool, 1)
  174. go func() {
  175. task.Handler.Call(args)
  176. ch <- true
  177. }()
  178. select {
  179. case <-ctx.Done():
  180. logging.LogWarnf("task [%s] timeout", task.Action)
  181. case <-ch:
  182. //logging.LogInfof("task [%s] done", task.Action)
  183. }
  184. currentTaskAction = ""
  185. }