manager.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. // Copyright 2021-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 pubsub
  15. import (
  16. "regexp"
  17. "sync"
  18. "github.com/lf-edge/ekuiper/internal/conf"
  19. "github.com/lf-edge/ekuiper/internal/xsql"
  20. "github.com/lf-edge/ekuiper/pkg/api"
  21. )
  22. const IdProperty = "topic"
  23. type pubConsumers struct {
  24. count int
  25. consumers map[string]chan api.SourceTuple // The consumer channel list [sourceId]chan
  26. }
  27. type subChan struct {
  28. regex *regexp.Regexp
  29. ch chan api.SourceTuple
  30. }
  31. var (
  32. pubTopics = make(map[string]*pubConsumers)
  33. subExps = make(map[string]*subChan)
  34. mu = sync.RWMutex{}
  35. )
  36. func CreatePub(topic string) {
  37. mu.Lock()
  38. defer mu.Unlock()
  39. if c, exists := pubTopics[topic]; exists {
  40. c.count += 1
  41. return
  42. }
  43. c := &pubConsumers{
  44. count: 1,
  45. consumers: make(map[string]chan api.SourceTuple),
  46. }
  47. pubTopics[topic] = c
  48. for sourceId, sc := range subExps {
  49. if sc.regex.MatchString(topic) {
  50. addPubConsumer(topic, sourceId, sc.ch)
  51. }
  52. }
  53. }
  54. func CreateSub(wildcard string, regex *regexp.Regexp, sourceId string, bufferLength int) chan api.SourceTuple {
  55. mu.Lock()
  56. defer mu.Unlock()
  57. ch := make(chan api.SourceTuple, bufferLength)
  58. if regex != nil {
  59. subExps[sourceId] = &subChan{
  60. regex: regex,
  61. ch: ch,
  62. }
  63. for topic := range pubTopics {
  64. if regex.MatchString(topic) {
  65. addPubConsumer(topic, sourceId, ch)
  66. }
  67. }
  68. } else {
  69. addPubConsumer(wildcard, sourceId, ch)
  70. }
  71. return ch
  72. }
  73. func CloseSourceConsumerChannel(topic string, sourceId string) {
  74. mu.Lock()
  75. defer mu.Unlock()
  76. if sc, exists := subExps[sourceId]; exists {
  77. close(sc.ch)
  78. delete(subExps, sourceId)
  79. for _, c := range pubTopics {
  80. removePubConsumer(topic, sourceId, c)
  81. }
  82. } else {
  83. if sinkConsumerChannels, exists := pubTopics[topic]; exists {
  84. removePubConsumer(topic, sourceId, sinkConsumerChannels)
  85. }
  86. }
  87. }
  88. func RemovePub(topic string) {
  89. mu.Lock()
  90. defer mu.Unlock()
  91. if sinkConsumerChannels, exists := pubTopics[topic]; exists {
  92. sinkConsumerChannels.count -= 1
  93. if len(sinkConsumerChannels.consumers) == 0 && sinkConsumerChannels.count == 0 {
  94. delete(pubTopics, topic)
  95. }
  96. }
  97. }
  98. func Produce(ctx api.StreamContext, topic string, data map[string]interface{}) {
  99. doProduce(ctx, topic, api.NewDefaultSourceTupleWithTime(data, map[string]interface{}{"topic": topic}, conf.GetNow()))
  100. }
  101. func ProduceUpdatable(ctx api.StreamContext, topic string, data map[string]interface{}, rowkind string, keyval interface{}) {
  102. doProduce(ctx, topic, &UpdatableTuple{
  103. DefaultSourceTuple: api.NewDefaultSourceTupleWithTime(data, map[string]interface{}{"topic": topic}, conf.GetNow()),
  104. Rowkind: rowkind,
  105. Keyval: keyval,
  106. })
  107. }
  108. func doProduce(ctx api.StreamContext, topic string, data api.SourceTuple) {
  109. c, exists := pubTopics[topic]
  110. if !exists {
  111. return
  112. }
  113. logger := ctx.GetLogger()
  114. mu.RLock()
  115. defer mu.RUnlock()
  116. // broadcast to all consumers
  117. for name, out := range c.consumers {
  118. select {
  119. case out <- data:
  120. logger.Debugf("memory source broadcast from topic %s to %s done", topic, name)
  121. case <-ctx.Done():
  122. // rule stop so stop waiting
  123. default:
  124. logger.Errorf("memory source topic %s drop message to %s", topic, name)
  125. }
  126. }
  127. }
  128. func ProduceError(ctx api.StreamContext, topic string, err error) {
  129. c, exists := pubTopics[topic]
  130. if !exists {
  131. return
  132. }
  133. logger := ctx.GetLogger()
  134. mu.RLock()
  135. defer mu.RUnlock()
  136. // broadcast to all consumers
  137. for name, out := range c.consumers {
  138. select {
  139. case out <- &xsql.ErrorSourceTuple{Error: err}:
  140. logger.Debugf("memory source broadcast error from topic %s to %s done", topic, name)
  141. case <-ctx.Done():
  142. // rule stop so stop waiting
  143. default:
  144. logger.Errorf("memory source topic %s drop message to %s", topic, name)
  145. }
  146. }
  147. }
  148. func addPubConsumer(topic string, sourceId string, ch chan api.SourceTuple) {
  149. var sinkConsumerChannels *pubConsumers
  150. if c, exists := pubTopics[topic]; exists {
  151. sinkConsumerChannels = c
  152. } else {
  153. sinkConsumerChannels = &pubConsumers{
  154. consumers: make(map[string]chan api.SourceTuple),
  155. }
  156. pubTopics[topic] = sinkConsumerChannels
  157. }
  158. if _, exists := sinkConsumerChannels.consumers[sourceId]; exists {
  159. conf.Log.Warnf("create memory source consumer for %s which is already exists", sourceId)
  160. } else {
  161. sinkConsumerChannels.consumers[sourceId] = ch
  162. }
  163. }
  164. func removePubConsumer(topic string, sourceId string, c *pubConsumers) {
  165. if _, exists := c.consumers[sourceId]; exists {
  166. delete(c.consumers, sourceId)
  167. }
  168. if len(c.consumers) == 0 && c.count == 0 {
  169. delete(pubTopics, topic)
  170. }
  171. }
  172. // Reset For testing only
  173. func Reset() {
  174. pubTopics = make(map[string]*pubConsumers)
  175. subExps = make(map[string]*subChan)
  176. }