functionRuntime.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 xsql
  15. import (
  16. "sync"
  17. "github.com/lf-edge/ekuiper/internal/binder/function"
  18. "github.com/lf-edge/ekuiper/internal/topo/context"
  19. "github.com/lf-edge/ekuiper/pkg/api"
  20. "github.com/lf-edge/ekuiper/pkg/errorx"
  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 []*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. // Get Each funcId returns a single instance of the function
  39. // The funcId is assigned in operator instance level, thus each operator will have a single instance of the function
  40. func (fp *funcRuntime) Get(name string, funcId int) (api.Function, api.FunctionContext, error) {
  41. fp.Lock()
  42. defer fp.Unlock()
  43. if len(fp.regs) <= funcId {
  44. for i := len(fp.regs); i <= funcId; i++ {
  45. fp.regs = append(fp.regs, nil)
  46. }
  47. }
  48. if reg := fp.regs[funcId]; reg == nil {
  49. var (
  50. nf api.Function
  51. err error
  52. )
  53. // Check service extension and plugin extension if set
  54. nf, err = function.Function(name)
  55. if nf == nil {
  56. if err == nil {
  57. return nil, nil, errorx.NotFoundErr
  58. } else {
  59. return nil, nil, err
  60. }
  61. }
  62. fctx := context.NewDefaultFuncContext(fp.parentCtx, funcId)
  63. fp.regs[funcId] = &funcReg{
  64. ins: nf,
  65. ctx: fctx,
  66. }
  67. return nf, fctx, nil
  68. } else {
  69. return reg.ins, reg.ctx, nil
  70. }
  71. }