table_processor.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package operators
  2. import (
  3. "fmt"
  4. "github.com/emqx/kuiper/xsql"
  5. "github.com/emqx/kuiper/xstream/api"
  6. )
  7. type TableProcessor struct {
  8. //Pruned stream fields. Could be streamField(with data type info) or string
  9. defaultFieldProcessor
  10. isBatchInput bool // whether the inputs are batched, such as file which sends multiple messages at a batch. If batch input, only fires when EOF is received. This is mutual exclusive with retainSize.
  11. retainSize int // how many(maximum) messages to be retained for each output
  12. // States
  13. output xsql.WindowTuples // current batched message collection
  14. batchEmitted bool // if batch input, this is the signal for whether the last batch has emitted. If true, reinitialize.
  15. }
  16. func NewTableProcessor(name string, fields []interface{}, fs xsql.Fields, options *xsql.Options) (*TableProcessor, error) {
  17. p := &TableProcessor{
  18. output: xsql.WindowTuples{
  19. Emitter: name,
  20. Tuples: make([]xsql.Tuple, 0),
  21. },
  22. }
  23. p.defaultFieldProcessor = defaultFieldProcessor{
  24. streamFields: fields, aliasFields: fs, isBinary: false, timestampFormat: options.TIMESTAMP_FORMAT,
  25. }
  26. if options.RETAIN_SIZE > 0 {
  27. p.retainSize = options.RETAIN_SIZE
  28. p.isBatchInput = false
  29. } else if isBatch(options.TYPE) {
  30. p.isBatchInput = true
  31. }
  32. return p, nil
  33. }
  34. /*
  35. * input: *xsql.Tuple or BatchCount
  36. * output: WindowTuples
  37. */
  38. func (p *TableProcessor) Apply(ctx api.StreamContext, data interface{}, fv *xsql.FunctionValuer, _ *xsql.AggregateFunctionValuer) interface{} {
  39. logger := ctx.GetLogger()
  40. tuple, ok := data.(*xsql.Tuple)
  41. if !ok {
  42. return fmt.Errorf("expect *xsql.Tuple data type")
  43. }
  44. logger.Debugf("preprocessor receive %v", tuple)
  45. if p.batchEmitted {
  46. p.output.Tuples = make([]xsql.Tuple, 0)
  47. p.batchEmitted = false
  48. }
  49. if tuple.Message != nil {
  50. result, err := p.processField(tuple, fv)
  51. if err != nil {
  52. return fmt.Errorf("error in table processor: %s", err)
  53. }
  54. tuple.Message = result
  55. if p.retainSize > 0 && len(p.output.Tuples) == p.retainSize {
  56. p.output.Tuples = p.output.Tuples[1:]
  57. }
  58. p.output.Tuples = append(p.output.Tuples, *tuple)
  59. if !p.isBatchInput {
  60. return p.output
  61. }
  62. } else if p.isBatchInput { // EOF
  63. p.batchEmitted = true
  64. return p.output
  65. }
  66. return nil
  67. }
  68. func isBatch(t string) bool {
  69. return t == "file" || t == ""
  70. }