queue.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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 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. HistoryDatabaseIndexFull = "task.history.database.index.full" // 历史数据库重建索引
  81. HistoryDatabaseIndexCommit = "task.history.database.index.commit" // 历史数据库索引提交
  82. DatabaseIndexEmbedBlock = "task.database.index.embedBlock" // 数据库索引嵌入块
  83. ReloadUI = "task.reload.ui" // 重载 UI
  84. UpgradeUserGuide = "task.upgrade.userGuide" // 升级用户指南文档笔记本
  85. AssetContentDatabaseIndexFull = "task.asset.database.index.full" // 资源文件数据库重建索引
  86. AssetContentDatabaseIndexCommit = "task.asset.database.index.commit" // 资源文件数据库索引提交
  87. )
  88. // uniqueActions 描述了唯一的任务,即队列中只能存在一个在执行的任务。
  89. var uniqueActions = []string{
  90. RepoCheckout,
  91. DatabaseIndexFull,
  92. DatabaseIndexCommit,
  93. OCRImage,
  94. HistoryGenerateDoc,
  95. HistoryDatabaseIndexFull,
  96. HistoryDatabaseIndexCommit,
  97. DatabaseIndexEmbedBlock,
  98. AssetContentDatabaseIndexFull,
  99. AssetContentDatabaseIndexCommit,
  100. }
  101. func Contain(action string, moreActions ...string) bool {
  102. actions := append(moreActions, action)
  103. actions = gulu.Str.RemoveDuplicatedElem(actions)
  104. for _, task := range taskQueue {
  105. if gulu.Str.Contains(task.Action, actions) {
  106. return true
  107. }
  108. }
  109. return false
  110. }
  111. func StatusJob() {
  112. tasks := taskQueue
  113. var items []map[string]interface{}
  114. count := map[string]int{}
  115. actionLangs := util.TaskActionLangs[util.Lang]
  116. for _, task := range tasks {
  117. action := task.Action
  118. if c := count[action]; 2 < c {
  119. logging.LogWarnf("too many tasks [%s], ignore show its status", action)
  120. continue
  121. }
  122. count[action]++
  123. if nil != actionLangs {
  124. if label := actionLangs[task.Action]; nil != label {
  125. action = label.(string)
  126. }
  127. }
  128. item := map[string]interface{}{"action": action}
  129. items = append(items, item)
  130. }
  131. if "" != currentTaskAction {
  132. if nil != actionLangs {
  133. if label := actionLangs[currentTaskAction]; nil != label {
  134. items = append([]map[string]interface{}{{"action": label.(string)}}, items...)
  135. }
  136. }
  137. }
  138. if 1 > len(items) {
  139. items = []map[string]interface{}{}
  140. }
  141. data := map[string]interface{}{}
  142. data["tasks"] = items
  143. util.PushBackgroundTask(data)
  144. }
  145. func ExecTaskJob() {
  146. task := popTask()
  147. if nil == task {
  148. return
  149. }
  150. if util.IsExiting {
  151. return
  152. }
  153. execTask(task)
  154. }
  155. func popTask() (ret *Task) {
  156. queueLock.Lock()
  157. defer queueLock.Unlock()
  158. if 0 == len(taskQueue) {
  159. return
  160. }
  161. ret = taskQueue[0]
  162. taskQueue = taskQueue[1:]
  163. return
  164. }
  165. var currentTaskAction string
  166. func execTask(task *Task) {
  167. defer logging.Recover()
  168. args := make([]reflect.Value, len(task.Args))
  169. for i, v := range task.Args {
  170. if nil == v {
  171. args[i] = reflect.New(task.Handler.Type().In(i)).Elem()
  172. } else {
  173. args[i] = reflect.ValueOf(v)
  174. }
  175. }
  176. currentTaskAction = task.Action
  177. ctx, cancel := context.WithTimeout(context.Background(), task.Timeout)
  178. defer cancel()
  179. ch := make(chan bool, 1)
  180. go func() {
  181. task.Handler.Call(args)
  182. ch <- true
  183. }()
  184. select {
  185. case <-ctx.Done():
  186. logging.LogWarnf("task [%s] timeout", task.Action)
  187. case <-ch:
  188. //logging.LogInfof("task [%s] done", task.Action)
  189. }
  190. currentTaskAction = ""
  191. }