operations.go 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. package nodes
  2. import (
  3. "fmt"
  4. "github.com/emqx/kuiper/xsql"
  5. "github.com/emqx/kuiper/xstream/api"
  6. "sync"
  7. )
  8. // UnOperation interface represents unary operations (i.e. Map, Filter, etc)
  9. type UnOperation interface {
  10. Apply(ctx api.StreamContext, data interface{}, fv *xsql.FunctionValuer, afv *xsql.AggregateFunctionValuer) interface{}
  11. }
  12. // UnFunc implements UnOperation as type func (context.Context, interface{})
  13. type UnFunc func(api.StreamContext, interface{}) interface{}
  14. // Apply implements UnOperation.Apply method
  15. func (f UnFunc) Apply(ctx api.StreamContext, data interface{}) interface{} {
  16. return f(ctx, data)
  17. }
  18. type UnaryOperator struct {
  19. *defaultSinkNode
  20. op UnOperation
  21. funcRegisters []xsql.FunctionRegister
  22. mutex sync.RWMutex
  23. cancelled bool
  24. }
  25. // NewUnary creates *UnaryOperator value
  26. func New(name string, registers []xsql.FunctionRegister, options *api.RuleOption) *UnaryOperator {
  27. return &UnaryOperator{
  28. funcRegisters: registers,
  29. defaultSinkNode: &defaultSinkNode{
  30. input: make(chan interface{}, options.BufferLength),
  31. defaultNode: &defaultNode{
  32. name: name,
  33. outputs: make(map[string]chan<- interface{}),
  34. concurrency: 1,
  35. sendError: options.SendError,
  36. },
  37. },
  38. }
  39. }
  40. // SetOperation sets the executor operation
  41. func (o *UnaryOperator) SetOperation(op UnOperation) {
  42. o.op = op
  43. }
  44. // Exec is the entry point for the executor
  45. func (o *UnaryOperator) Exec(ctx api.StreamContext, errCh chan<- error) {
  46. o.ctx = ctx
  47. log := ctx.GetLogger()
  48. log.Debugf("Unary operator %s is started", o.name)
  49. if len(o.outputs) <= 0 {
  50. go func() { errCh <- fmt.Errorf("no output channel found") }()
  51. return
  52. }
  53. // validate p
  54. if o.concurrency < 1 {
  55. o.concurrency = 1
  56. }
  57. //reset status
  58. o.statManagers = nil
  59. for i := 0; i < o.concurrency; i++ { // workers
  60. instance := i
  61. go o.doOp(ctx.WithInstance(instance), errCh)
  62. }
  63. }
  64. func (o *UnaryOperator) doOp(ctx api.StreamContext, errCh chan<- error) {
  65. logger := ctx.GetLogger()
  66. if o.op == nil {
  67. logger.Infoln("Unary operator missing operation")
  68. return
  69. }
  70. exeCtx, cancel := ctx.WithCancel()
  71. defer func() {
  72. logger.Infof("unary operator %s instance %d done, cancelling future items", o.name, ctx.GetInstanceId())
  73. cancel()
  74. }()
  75. stats, err := NewStatManager("op", ctx)
  76. if err != nil {
  77. o.drainError(errCh, err, ctx)
  78. return
  79. }
  80. o.mutex.Lock()
  81. o.statManagers = append(o.statManagers, stats)
  82. o.mutex.Unlock()
  83. fv, afv := xsql.NewFunctionValuersForOp(exeCtx, o.funcRegisters)
  84. for {
  85. select {
  86. // process incoming item
  87. case item := <-o.input:
  88. processed := false
  89. if item, processed = o.preprocess(item); processed {
  90. break
  91. }
  92. stats.IncTotalRecordsIn()
  93. stats.ProcessTimeStart()
  94. result := o.op.Apply(exeCtx, item, fv, afv)
  95. switch val := result.(type) {
  96. case nil:
  97. continue
  98. case error:
  99. logger.Errorf("Operation %s error: %s", ctx.GetOpId(), val)
  100. o.Broadcast(val)
  101. stats.IncTotalExceptions()
  102. continue
  103. default:
  104. stats.ProcessTimeEnd()
  105. o.Broadcast(val)
  106. stats.IncTotalRecordsOut()
  107. stats.SetBufferLength(int64(len(o.input)))
  108. }
  109. // is cancelling
  110. case <-ctx.Done():
  111. logger.Infof("unary operator %s instance %d cancelling....", o.name, ctx.GetInstanceId())
  112. o.mutex.Lock()
  113. cancel()
  114. o.cancelled = true
  115. o.mutex.Unlock()
  116. return
  117. }
  118. }
  119. }
  120. func (o *UnaryOperator) drainError(errCh chan<- error, err error, ctx api.StreamContext) {
  121. go func() {
  122. select {
  123. case errCh <- err:
  124. ctx.GetLogger().Errorf("unary operator %s error %s", o.name, err)
  125. case <-ctx.Done():
  126. // stop waiting
  127. }
  128. }()
  129. }