functionRuntime.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright 2021 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 xsql
  15. import (
  16. "github.com/lf-edge/ekuiper/internal/topo/context"
  17. "github.com/lf-edge/ekuiper/pkg/api"
  18. "github.com/lf-edge/ekuiper/pkg/errorx"
  19. "sync"
  20. )
  21. //Manage the function plugin instances
  22. //Each operator has a single instance of this to hold the context
  23. type funcRuntime struct {
  24. sync.Mutex
  25. regs map[string]*funcReg
  26. parentCtx api.StreamContext
  27. funcRegisters []FunctionRegister
  28. }
  29. type funcReg struct {
  30. ins api.Function
  31. ctx api.FunctionContext
  32. }
  33. func NewFuncRuntime(ctx api.StreamContext, registers []FunctionRegister) *funcRuntime {
  34. return &funcRuntime{
  35. parentCtx: ctx,
  36. funcRegisters: registers,
  37. }
  38. }
  39. func (fp *funcRuntime) Get(name string) (api.Function, api.FunctionContext, error) {
  40. fp.Lock()
  41. defer fp.Unlock()
  42. if fp.regs == nil {
  43. fp.regs = make(map[string]*funcReg)
  44. }
  45. if reg, ok := fp.regs[name]; !ok {
  46. var (
  47. nf api.Function
  48. err error
  49. )
  50. // Check service extension and plugin extension if set
  51. for _, r := range fp.funcRegisters {
  52. if r.HasFunction(name) {
  53. nf, err = r.Function(name)
  54. if err != nil {
  55. return nil, nil, err
  56. }
  57. break
  58. }
  59. }
  60. if nf == nil {
  61. return nil, nil, errorx.NotFoundErr
  62. }
  63. fctx := context.NewDefaultFuncContext(fp.parentCtx, len(fp.regs))
  64. fp.regs[name] = &funcReg{
  65. ins: nf,
  66. ctx: fctx,
  67. }
  68. return nf, fctx, nil
  69. } else {
  70. return reg.ins, reg.ctx, nil
  71. }
  72. }