You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

queue_channel.go 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package queue
  5. import (
  6. "context"
  7. "fmt"
  8. "code.gitea.io/gitea/modules/log"
  9. )
  10. // ChannelQueueType is the type for channel queue
  11. const ChannelQueueType Type = "channel"
  12. // ChannelQueueConfiguration is the configuration for a ChannelQueue
  13. type ChannelQueueConfiguration struct {
  14. WorkerPoolConfiguration
  15. Workers int
  16. Name string
  17. }
  18. // ChannelQueue implements Queue
  19. //
  20. // A channel queue is not persistable and does not shutdown or terminate cleanly
  21. // It is basically a very thin wrapper around a WorkerPool
  22. type ChannelQueue struct {
  23. *WorkerPool
  24. exemplar interface{}
  25. workers int
  26. name string
  27. }
  28. // NewChannelQueue creates a memory channel queue
  29. func NewChannelQueue(handle HandlerFunc, cfg, exemplar interface{}) (Queue, error) {
  30. configInterface, err := toConfig(ChannelQueueConfiguration{}, cfg)
  31. if err != nil {
  32. return nil, err
  33. }
  34. config := configInterface.(ChannelQueueConfiguration)
  35. if config.BatchLength == 0 {
  36. config.BatchLength = 1
  37. }
  38. queue := &ChannelQueue{
  39. WorkerPool: NewWorkerPool(handle, config.WorkerPoolConfiguration),
  40. exemplar: exemplar,
  41. workers: config.Workers,
  42. name: config.Name,
  43. }
  44. queue.qid = GetManager().Add(queue, ChannelQueueType, config, exemplar)
  45. return queue, nil
  46. }
  47. // Run starts to run the queue
  48. func (q *ChannelQueue) Run(atShutdown, atTerminate func(context.Context, func())) {
  49. atShutdown(context.Background(), func() {
  50. log.Warn("ChannelQueue: %s is not shutdownable!", q.name)
  51. })
  52. atTerminate(context.Background(), func() {
  53. log.Warn("ChannelQueue: %s is not terminatable!", q.name)
  54. })
  55. log.Debug("ChannelQueue: %s Starting", q.name)
  56. go func() {
  57. _ = q.AddWorkers(q.workers, 0)
  58. }()
  59. }
  60. // Push will push data into the queue
  61. func (q *ChannelQueue) Push(data Data) error {
  62. if !assignableTo(data, q.exemplar) {
  63. return fmt.Errorf("Unable to assign data: %v to same type as exemplar: %v in queue: %s", data, q.exemplar, q.name)
  64. }
  65. q.WorkerPool.Push(data)
  66. return nil
  67. }
  68. // Name returns the name of this queue
  69. func (q *ChannelQueue) Name() string {
  70. return q.name
  71. }
  72. func init() {
  73. queuesMap[ChannelQueueType] = NewChannelQueue
  74. }