functionRuntime.go 1.8 KB

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