join_align_node.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. // Copyright 2021-2022 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package node
  15. import (
  16. "fmt"
  17. "github.com/lf-edge/ekuiper/internal/topo/node/metric"
  18. "github.com/lf-edge/ekuiper/internal/xsql"
  19. "github.com/lf-edge/ekuiper/pkg/api"
  20. "github.com/lf-edge/ekuiper/pkg/infra"
  21. )
  22. // JoinAlignNode will block the stream and buffer all the table tuples. Once buffered, it will combine the later input with the buffer
  23. // The input for batch table MUST be *WindowTuples
  24. type JoinAlignNode struct {
  25. *defaultSinkNode
  26. statManager metric.StatManager
  27. emitters map[string]int
  28. // states
  29. batch *xsql.WindowTuplesSet
  30. }
  31. const BatchKey = "$$batchInputs"
  32. func NewJoinAlignNode(name string, emitters []string, options *api.RuleOption) (*JoinAlignNode, error) {
  33. emap := make(map[string]int, len(emitters))
  34. for i, e := range emitters {
  35. emap[e] = i
  36. }
  37. n := &JoinAlignNode{
  38. emitters: emap,
  39. }
  40. n.defaultSinkNode = &defaultSinkNode{
  41. input: make(chan interface{}, options.BufferLength),
  42. defaultNode: &defaultNode{
  43. outputs: make(map[string]chan<- interface{}),
  44. name: name,
  45. sendError: options.SendError,
  46. },
  47. }
  48. return n, nil
  49. }
  50. func (n *JoinAlignNode) Exec(ctx api.StreamContext, errCh chan<- error) {
  51. n.ctx = ctx
  52. log := ctx.GetLogger()
  53. log.Debugf("JoinAlignNode %s is started", n.name)
  54. if len(n.outputs) <= 0 {
  55. infra.DrainError(ctx, fmt.Errorf("no output channel found"), errCh)
  56. return
  57. }
  58. stats, err := metric.NewStatManager(ctx, "op")
  59. if err != nil {
  60. infra.DrainError(ctx, fmt.Errorf("no output channel found"), errCh)
  61. return
  62. }
  63. n.statManager = stats
  64. go func() {
  65. err := infra.SafeRun(func() error {
  66. // restore batch state
  67. if s, err := ctx.GetState(BatchKey); err == nil {
  68. switch st := s.(type) {
  69. case []xsql.WindowTuples:
  70. if len(st) == len(n.emitters) {
  71. n.batch = &xsql.WindowTuplesSet{Content: st}
  72. log.Infof("Restore batch state %+v", st)
  73. } else {
  74. log.Warnf("Restore batch state got different emitter length so discarded: %+v", st)
  75. }
  76. case nil:
  77. log.Debugf("Restore batch state, nothing")
  78. default:
  79. infra.DrainError(ctx, fmt.Errorf("restore batch state %v error, invalid type", st), errCh)
  80. }
  81. } else {
  82. log.Warnf("Restore batch state fails: %s", err)
  83. }
  84. if n.batch == nil {
  85. n.batch = &xsql.WindowTuplesSet{
  86. Content: make([]xsql.WindowTuples, len(n.emitters)),
  87. }
  88. }
  89. for {
  90. log.Debugf("JoinAlignNode %s is looping", n.name)
  91. select {
  92. // process incoming item from both streams(transformed) and tables
  93. case item, opened := <-n.input:
  94. processed := false
  95. if item, processed = n.preprocess(item); processed {
  96. break
  97. }
  98. n.statManager.IncTotalRecordsIn()
  99. n.statManager.ProcessTimeStart()
  100. if !opened {
  101. n.statManager.IncTotalExceptions()
  102. break
  103. }
  104. switch d := item.(type) {
  105. case error:
  106. n.Broadcast(d)
  107. n.statManager.IncTotalExceptions()
  108. case *xsql.Tuple:
  109. log.Debugf("JoinAlignNode receive tuple input %s", d)
  110. temp := xsql.WindowTuplesSet{
  111. Content: make([]xsql.WindowTuples, 0),
  112. }
  113. temp = temp.AddTuple(d)
  114. n.alignBatch(ctx, temp)
  115. case xsql.WindowTuplesSet:
  116. log.Debugf("JoinAlignNode receive window input %s", d)
  117. n.alignBatch(ctx, d)
  118. case xsql.WindowTuples: // batch input
  119. log.Debugf("JoinAlignNode receive batch source %s", d)
  120. // Buffer and update batch inputs
  121. index, ok := n.emitters[d.Emitter]
  122. if !ok {
  123. n.Broadcast(fmt.Errorf("run JoinAlignNode error: receive batch input from unknown emitter %[1]T(%[1]v)", d))
  124. n.statManager.IncTotalExceptions()
  125. }
  126. if n.batch != nil && len(n.batch.Content) > index {
  127. n.batch.Content[index] = d
  128. ctx.PutState(BatchKey, n.batch)
  129. } else {
  130. log.Errorf("Invalid index %d for batch %v", index, n.batch)
  131. }
  132. default:
  133. n.Broadcast(fmt.Errorf("run JoinAlignNode error: invalid input type but got %[1]T(%[1]v)", d))
  134. n.statManager.IncTotalExceptions()
  135. }
  136. case <-ctx.Done():
  137. log.Infoln("Cancelling join align node....")
  138. return nil
  139. }
  140. }
  141. })
  142. if err != nil {
  143. infra.DrainError(ctx, err, errCh)
  144. }
  145. }()
  146. }
  147. func (n *JoinAlignNode) alignBatch(_ api.StreamContext, w xsql.WindowTuplesSet) {
  148. n.statManager.ProcessTimeStart()
  149. w.Content = append(w.Content, n.batch.Content...)
  150. n.Broadcast(w)
  151. n.statManager.ProcessTimeEnd()
  152. n.statManager.IncTotalRecordsOut()
  153. n.statManager.SetBufferLength(int64(len(n.input)))
  154. }
  155. func (n *JoinAlignNode) GetMetrics() [][]interface{} {
  156. if n.statManager != nil {
  157. return [][]interface{}{
  158. n.statManager.GetMetrics(),
  159. }
  160. } else {
  161. return nil
  162. }
  163. }