queue.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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. "github.com/siyuan-note/siyuan/kernel/util"
  20. "reflect"
  21. "sync"
  22. "time"
  23. "github.com/siyuan-note/logging"
  24. )
  25. var (
  26. taskQueue []*Task
  27. taskQueueStatus int
  28. queueLock = sync.Mutex{}
  29. )
  30. const (
  31. QueueStatusRunning = iota
  32. QueueStatusClosing
  33. )
  34. type Task struct {
  35. Action string
  36. Handler reflect.Value
  37. Args []interface{}
  38. Created time.Time
  39. }
  40. func PrependTask(action string, handler interface{}, args ...interface{}) {
  41. queueLock.Lock()
  42. defer queueLock.Unlock()
  43. if QueueStatusRunning != taskQueueStatus {
  44. //logging.LogWarnf("task queue is paused, action [%s] will be ignored", action)
  45. return
  46. }
  47. cancelTask(action, args...)
  48. taskQueue = append([]*Task{newTask(action, handler, args...)}, taskQueue...)
  49. }
  50. func AppendTask(action string, handler interface{}, args ...interface{}) {
  51. queueLock.Lock()
  52. defer queueLock.Unlock()
  53. if QueueStatusRunning != taskQueueStatus {
  54. //logging.LogWarnf("task queue is paused, action [%s] will be ignored", action)
  55. return
  56. }
  57. cancelTask(action, args...)
  58. taskQueue = append(taskQueue, newTask(action, handler, args...))
  59. }
  60. func cancelTask(action string, args ...interface{}) {
  61. for i := len(taskQueue) - 1; i >= 0; i-- {
  62. task := taskQueue[i]
  63. if action == task.Action {
  64. if len(task.Args) != len(args) {
  65. continue
  66. }
  67. for j, arg := range args {
  68. if arg != task.Args[j] {
  69. continue
  70. }
  71. }
  72. taskQueue = append(taskQueue[:i], taskQueue[i+1:]...)
  73. break
  74. }
  75. }
  76. }
  77. func newTask(action string, handler interface{}, args ...interface{}) *Task {
  78. return &Task{
  79. Action: action,
  80. Handler: reflect.ValueOf(handler),
  81. Args: args,
  82. Created: time.Now(),
  83. }
  84. }
  85. const (
  86. RepoCheckout = "task.repo.checkout" // 从快照中检出
  87. DatabaseIndexFull = "task.database.index.full" // 重建索引
  88. DatabaseIndex = "task.database.index" // 数据库索引
  89. DatabaseIndexCommit = "task.database.index.commit" // 数据库索引提交
  90. DatabaseIndexRef = "task.database.index.ref" // 数据库索引引用
  91. DatabaseIndexFix = "task.database.index.fix" // 数据库索引订正
  92. OCRImage = "task.ocr.image" // 图片 OCR 提取文本
  93. HistoryGenerateDoc = "task.history.generateDoc" // 生成文件历史
  94. DatabaseIndexEmbedBlock = "task.database.index.embedBlock" // 数据库索引嵌入块
  95. )
  96. func ContainIndexTask() bool {
  97. for _, task := range taskQueue {
  98. if DatabaseIndex == task.Action || DatabaseIndexFull == task.Action {
  99. return true
  100. }
  101. }
  102. return false
  103. }
  104. func StatusLoop() {
  105. for {
  106. time.Sleep(5 * time.Second)
  107. tasks := taskQueue
  108. data := map[string]interface{}{}
  109. var items []map[string]interface{}
  110. for _, task := range tasks {
  111. if OCRImage == task.Action || DatabaseIndexEmbedBlock == task.Action {
  112. continue
  113. }
  114. actionLangs := util.TaskActionLangs[util.Lang]
  115. action := task.Action
  116. if nil != actionLangs {
  117. if label := actionLangs[task.Action]; nil != label {
  118. action = label.(string)
  119. }
  120. }
  121. item := map[string]interface{}{
  122. "action": action,
  123. }
  124. items = append(items, item)
  125. }
  126. if 1 > len(items) {
  127. items = []map[string]interface{}{}
  128. }
  129. data["tasks"] = items
  130. util.PushBackgroundTask(data)
  131. }
  132. }
  133. func Loop() {
  134. for {
  135. time.Sleep(100 * time.Millisecond)
  136. if QueueStatusClosing == taskQueueStatus {
  137. clearQueue()
  138. break
  139. }
  140. task := popTask()
  141. if nil == task {
  142. continue
  143. }
  144. if util.IsExiting {
  145. break
  146. }
  147. execTask(task)
  148. }
  149. }
  150. func clearQueue() {
  151. queueLock.Lock()
  152. defer queueLock.Unlock()
  153. taskQueue = []*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. func execTask(task *Task) {
  166. defer logging.Recover()
  167. args := make([]reflect.Value, len(task.Args))
  168. for i, v := range task.Args {
  169. if nil == v {
  170. args[i] = reflect.New(task.Handler.Type().In(i)).Elem()
  171. } else {
  172. args[i] = reflect.ValueOf(v)
  173. }
  174. }
  175. ctx, cancel := context.WithTimeout(context.Background(), time.Second*12)
  176. defer cancel()
  177. ch := make(chan bool, 1)
  178. go func() {
  179. task.Handler.Call(args)
  180. ch <- true
  181. }()
  182. select {
  183. case <-ctx.Done():
  184. //logging.LogWarnf("task [%s] timeout", task.Action)
  185. case <-ch:
  186. //logging.LogInfof("task [%s] done", task.Action)
  187. }
  188. }