default.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. // Copyright 2022-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. package context
  15. import (
  16. "bytes"
  17. "context"
  18. "fmt"
  19. "regexp"
  20. "sync"
  21. "text/template"
  22. "time"
  23. "github.com/sirupsen/logrus"
  24. "github.com/lf-edge/ekuiper/internal/conf"
  25. "github.com/lf-edge/ekuiper/internal/topo/transform"
  26. "github.com/lf-edge/ekuiper/pkg/api"
  27. "github.com/lf-edge/ekuiper/pkg/cast"
  28. )
  29. const LoggerKey = "$$logger"
  30. type DefaultContext struct {
  31. ruleId string
  32. opId string
  33. instanceId int
  34. ctx context.Context
  35. err error
  36. // Only initialized after withMeta set
  37. store api.Store
  38. state *sync.Map
  39. snapshot map[string]interface{}
  40. // cache
  41. tpReg sync.Map
  42. jpReg sync.Map
  43. }
  44. func Background() *DefaultContext {
  45. c := &DefaultContext{
  46. ctx: context.Background(),
  47. }
  48. return c
  49. }
  50. func WithValue(parent *DefaultContext, key, val interface{}) *DefaultContext {
  51. parent.ctx = context.WithValue(parent.ctx, key, val)
  52. return parent
  53. }
  54. // Implement context interface
  55. func (c *DefaultContext) Deadline() (deadline time.Time, ok bool) {
  56. return c.ctx.Deadline()
  57. }
  58. func (c *DefaultContext) Done() <-chan struct{} {
  59. return c.ctx.Done()
  60. }
  61. func (c *DefaultContext) Err() error {
  62. if c.err != nil {
  63. return c.err
  64. }
  65. return c.ctx.Err()
  66. }
  67. func (c *DefaultContext) Value(key interface{}) interface{} {
  68. return c.ctx.Value(key)
  69. }
  70. func (c *DefaultContext) GetContext() context.Context {
  71. return c.ctx
  72. }
  73. func (c *DefaultContext) GetLogger() api.Logger {
  74. l, ok := c.ctx.Value(LoggerKey).(*logrus.Entry)
  75. if l != nil && ok {
  76. return l
  77. }
  78. return conf.Log.WithField("caller", "default")
  79. }
  80. func (c *DefaultContext) GetRuleId() string {
  81. return c.ruleId
  82. }
  83. func (c *DefaultContext) GetOpId() string {
  84. return c.opId
  85. }
  86. func (c *DefaultContext) GetInstanceId() int {
  87. return c.instanceId
  88. }
  89. func (c *DefaultContext) GetRootPath() string {
  90. loc, _ := conf.GetLoc("")
  91. return loc
  92. }
  93. func (c *DefaultContext) SetError(err error) {
  94. c.err = err
  95. }
  96. // ParseTemplate parse template string against data
  97. // The templates are built only once and cached in the context by its raw string as the key
  98. // If the prop string is not a template, a nil template is cached to indicate it has been parsed, and it will return the original string
  99. func (c *DefaultContext) ParseTemplate(prop string, data interface{}) (string, error) {
  100. var (
  101. tp *template.Template
  102. err error
  103. )
  104. if raw, ok := c.tpReg.Load(prop); ok {
  105. if raw != nil {
  106. tp = raw.(*template.Template)
  107. } else {
  108. return prop, nil
  109. }
  110. } else { // not parsed before
  111. re := regexp.MustCompile(`{{(.*?)}}`)
  112. // check if it is a template
  113. if re.Match([]byte(prop)) {
  114. tp, err = transform.GenTp(prop)
  115. if err != nil {
  116. return fmt.Sprintf("%v", data), err
  117. }
  118. c.tpReg.Store(prop, tp)
  119. } else {
  120. c.tpReg.Store(prop, nil)
  121. return prop, nil
  122. }
  123. }
  124. var output bytes.Buffer
  125. err = tp.Execute(&output, data)
  126. if err != nil {
  127. return fmt.Sprintf("%v", data), err
  128. }
  129. return output.String(), nil
  130. }
  131. func (c *DefaultContext) ParseJsonPath(prop string, data interface{}) (interface{}, error) {
  132. var (
  133. je conf.JsonPathEval
  134. err error
  135. )
  136. if raw, ok := c.jpReg.Load(prop); ok {
  137. je = raw.(conf.JsonPathEval)
  138. } else {
  139. je, err = conf.GetJsonPathEval(prop)
  140. if err != nil {
  141. return nil, err
  142. }
  143. c.jpReg.Store(prop, je)
  144. }
  145. return je.Eval(data)
  146. }
  147. func (c *DefaultContext) WithMeta(ruleId string, opId string, store api.Store) api.StreamContext {
  148. s, err := store.GetOpState(opId)
  149. if err != nil {
  150. c.GetLogger().Warnf("Initialize context store error for %s: %s", opId, err)
  151. }
  152. return &DefaultContext{
  153. ruleId: ruleId,
  154. opId: opId,
  155. instanceId: 0,
  156. ctx: c.ctx,
  157. store: store,
  158. state: s,
  159. tpReg: sync.Map{},
  160. jpReg: sync.Map{},
  161. }
  162. }
  163. func (c *DefaultContext) WithInstance(instanceId int) api.StreamContext {
  164. return &DefaultContext{
  165. instanceId: instanceId,
  166. ruleId: c.ruleId,
  167. opId: c.opId,
  168. ctx: c.ctx,
  169. state: c.state,
  170. }
  171. }
  172. func (c *DefaultContext) WithCancel() (api.StreamContext, context.CancelFunc) {
  173. ctx, cancel := context.WithCancel(c.ctx)
  174. return &DefaultContext{
  175. ruleId: c.ruleId,
  176. opId: c.opId,
  177. instanceId: c.instanceId,
  178. ctx: ctx,
  179. state: c.state,
  180. }, cancel
  181. }
  182. func (c *DefaultContext) IncrCounter(key string, amount int) error {
  183. if v, ok := c.state.Load(key); ok {
  184. if vi, err := cast.ToInt(v, cast.STRICT); err != nil {
  185. return fmt.Errorf("state[%s] must be an int", key)
  186. } else {
  187. c.state.Store(key, vi+amount)
  188. }
  189. } else {
  190. c.state.Store(key, amount)
  191. }
  192. return nil
  193. }
  194. func (c *DefaultContext) GetCounter(key string) (int, error) {
  195. if v, ok := c.state.Load(key); ok {
  196. if vi, err := cast.ToInt(v, cast.STRICT); err != nil {
  197. return 0, fmt.Errorf("state[%s] is not a number, but %v", key, v)
  198. } else {
  199. return vi, nil
  200. }
  201. } else {
  202. c.state.Store(key, 0)
  203. return 0, nil
  204. }
  205. }
  206. func (c *DefaultContext) PutState(key string, value interface{}) error {
  207. c.state.Store(key, value)
  208. return nil
  209. }
  210. func (c *DefaultContext) GetState(key string) (interface{}, error) {
  211. if v, ok := c.state.Load(key); ok {
  212. return v, nil
  213. } else {
  214. return nil, nil
  215. }
  216. }
  217. func (c *DefaultContext) DeleteState(key string) error {
  218. c.state.Delete(key)
  219. return nil
  220. }
  221. func (c *DefaultContext) Snapshot() error {
  222. c.snapshot = cast.SyncMapToMap(c.state)
  223. return nil
  224. }
  225. func (c *DefaultContext) SaveState(checkpointId int64) error {
  226. err := c.store.SaveState(checkpointId, c.opId, c.snapshot)
  227. if err != nil {
  228. return err
  229. }
  230. c.snapshot = nil
  231. return nil
  232. }