queue.go 6.4 KB

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