script_operator.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright 2023 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. //go:build script
  15. package operator
  16. import (
  17. "fmt"
  18. "github.com/dop251/goja"
  19. "github.com/lf-edge/ekuiper/internal/xsql"
  20. "github.com/lf-edge/ekuiper/pkg/api"
  21. )
  22. type ScriptOp struct {
  23. vm *goja.Runtime
  24. jsfunc goja.Callable
  25. }
  26. func NewScriptOp(script string) (*ScriptOp, error) {
  27. vm := goja.New()
  28. _, err := vm.RunString(script)
  29. if err != nil {
  30. return nil, fmt.Errorf("failed to interprete script: %v", err)
  31. }
  32. exec, ok := goja.AssertFunction(vm.Get("exec"))
  33. if !ok {
  34. return nil, fmt.Errorf("cannot find function \"exec\" in script")
  35. }
  36. n := &ScriptOp{
  37. vm: vm,
  38. jsfunc: exec,
  39. }
  40. return n, nil
  41. }
  42. func (p *ScriptOp) Apply(ctx api.StreamContext, data interface{}, _ *xsql.FunctionValuer, _ *xsql.AggregateFunctionValuer) interface{} {
  43. ctx.GetLogger().Debugf("ScriptOp receive: %s", data)
  44. switch input := data.(type) {
  45. case error:
  46. return input
  47. case *xsql.Tuple:
  48. val, err := p.jsfunc(goja.Undefined(), p.vm.ToValue(input.ToMap()), p.vm.ToValue(input.Metadata))
  49. if err != nil {
  50. return fmt.Errorf("failed to execute script: %v", err)
  51. } else {
  52. nm, ok := val.Export().(map[string]interface{})
  53. if !ok {
  54. return fmt.Errorf("script exec result is not a map: %v", val.Export())
  55. } else {
  56. return &xsql.Tuple{Message: nm, Metadata: input.Metadata, Emitter: input.Emitter, Timestamp: input.Timestamp}
  57. }
  58. }
  59. default:
  60. return fmt.Errorf("run script op invalid input allow tuple only but got %[1]T(%[1]v)", input)
  61. }
  62. return data
  63. }