functionRuntime.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. "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 []*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, funcId int) (api.Function, api.FunctionContext, error) {
  39. fp.Lock()
  40. defer fp.Unlock()
  41. if len(fp.regs) <= funcId {
  42. for i := len(fp.regs); i <= funcId; i++ {
  43. fp.regs = append(fp.regs, nil)
  44. }
  45. }
  46. if reg := fp.regs[funcId]; reg == nil {
  47. var (
  48. nf api.Function
  49. err error
  50. )
  51. // Check service extension and plugin extension if set
  52. nf, err = function.Function(name)
  53. if nf == nil {
  54. if err == nil {
  55. return nil, nil, errorx.NotFoundErr
  56. } else {
  57. return nil, nil, err
  58. }
  59. }
  60. fctx := context.NewDefaultFuncContext(fp.parentCtx, funcId)
  61. fp.regs[funcId] = &funcReg{
  62. ins: nf,
  63. ctx: fctx,
  64. }
  65. return nf, fctx, nil
  66. } else {
  67. return reg.ins, reg.ctx, nil
  68. }
  69. }